memostack
article thumbnail
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
반응형

Infix Functions (중위 함수)

중위 함수를 생성할 때는 infix fun 예약어를 사용한다.

fun main() {
    // Infix 함수 정의
    infix fun Int.times(message: String) = message.repeat(this)
    // 'Bye' 를 2번 반복해서 출력하는 중위 함수(Infix Functions)
    println(2.times("Bye "))
    println(2 times "Bye ") // .과 ()를 생략하여 표현 할 수 있음
}

원래는 Int.times(String) 형태로 호출하지만, .()를 생략하여 표현 할 수 있음

Bye Bye 
Bye Bye 
  • 결과 동일

다른 예시

fun main() {
    println("Ferrari" to "Katrina")
    println("Ferrari".to("Katrina"))
}

위 2개 방식 모두 동일한 코드이며, 동일한 결과를 보여줌

 

fun main() {
    val sophia = Person("Sophia")
    val claudia = Person("Claudia")
    sophia likes claudia
}

class Person(val name: String) {
    val likedPeople = mutableListOf<Person>()
    infix fun likes(other: Person) {
        likedPeople.add(other)
    }
}

클래스 내부에 infix 함수를 생성하여, Person likes Person과 같이 사용 가능

 

Operator Functions (연산자 함수)

 

Arithmetic operators

operator fun 예약어와 plus(), minus(), times(), div() 등 의 메소드를 이용하여 +, -, *, / 를 정의할 수 있다

fun main() {
    operator fun Int.times(message: String) = message.repeat(this)
    println(3 * "Bye ")
}
Bye Bye Bye 

 

varargs (가변 인자)

varargs 예약어를 사용하여 가변 인자를 만들 수 있다

아래 예제와 같이 인자를 원하는 만큼 넣을 수 있다.

fun main() {
    printAll("Hello")
    printAll("Hello", "Kotlin")
    printAll("Hello", "Hallo", "안녕")
}

fun printAll(vararg messages: String) {
    for (msg in messages) print("$msg ")
    println()
}
Hello 
Hello Kotlin 
Hello Hallo 안녕 

 

다른 글

2021/03/01 - [Language/Kotlin] - Kotlin - 함수 (Default Parameter Values, Named Arguments)

 

Kotlin - 함수 (Default Parameter Values, Named Arguments)

Kotlin function 코틀린에서 함수를 생성할 때는 fun 키워드를 사용한다. fun main(args: Array ) { printMessage("World") printMessage("Kotlin") } fun printMessage(message: String): Unit { println("Hello,..

memostack.tistory.com

 

Reference

play.kotlinlang.org/byExample/01_introduction/02_Functions

 

Kotlin Playground: Edit, Run, Share Kotlin Code Online

 

play.kotlinlang.org

kotlinlang.org/docs/functions.html#infix-notation

 

Functions - Help | Kotlin

 

kotlinlang.org

kotlinlang.org/docs/operator-overloading.html#in-operator

 

Operator overloading - Help | Kotlin

 

kotlinlang.org

 

반응형
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
profile

memostack

@bluemiv_mm

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!