728x90
Infix
๋ ๊ฐ์ ๋ณ์ ์ฌ์ด์ ์ค๋ ํจ์
์กฐ๊ฑด
- ๋ฉค๋ฒ ํจ์์ด๊ฑฐ๋ ํ์ฅ ํจ์์ฌ์ผ ํจ
- ํ๋์ ๋งค๊ฐ๋ณ์๋ฅผ ๊ฐ์ ธ์ผ ํจ
- ๊ธฐ๋ณธ ๊ฐ์ ๊ฐ์ง ์ ์์ผ๋ฉฐ varargs ์ฌ์ฉ ๋ถ๊ฐ
์์ 1
infix fun Int.shl(x: Int): Int { ... }
// calling the function using the infix notation
1 shl 2
// is the same as
1.shl(2)
์์ 2
fun main() {
infix fun Int.times(str: String) = str.repeat(this) // 1
println(2 times "Bye ") // 2
val pair = "Ferrari" to "Katrina" // 3
println(pair)
infix fun String.onto(other: String) = Pair(this, other) // 4
val myPair = "McLaren" onto "Lucas"
println(myPair)
val sophia = Person("Sophia")
val claudia = Person("Claudia")
sophia likes claudia // 5
}
class Person(val name: String) {
val likedPeople = mutableListOf<Person>()
infix fun likes(other: Person) { likedPeople.add(other) } // 6
}
์ฃผ์ ์ฌํญ
Infix ํจ์๋ ์ฐ์ ์ฐ์ฐ์, ํ์ ์บ์คํธ, rangeTo ์ฐ์ฐ์๋ณด๋ค ๋ฎ์ ์ฐ์ ์์๋ฅผ ๊ฐ์ง๊ณ ์์
ex)
0 until n * 2 -> 0 until (n * 2)
๋ ํผ๋ฐ์ค
https://kotlinlang.org/docs/functions.html#infix-notation
https://play.kotlinlang.org/byExample/01_introduction/02_Functions
728x90