Kotlin Infix Functions
Infix functions
infix defines a function that supports infix notation. The example below defines an extension function named add on the Int class. It can be called as 3.add(5), and because it is marked with infix, it can also be used in infix notation as 3 add 5. Examples of infix functions defined this way include until, which creates a Range, and to, which creates a Pair.
infix fun Int.add(x: Int): Int {
return this + x
}
fun main() {
println(3.add(5)) // 8
println(3 add 5) // 8
}
An infix function is a function that appears between two variables. One of Kotlin’s built-in infix functions is to, which creates a Pair.
Look at the following code.
val pair : Pair<String, String> = "White" to "0xffffff"
Between the "White" and "0xffffff" objects, to is the infix function. to creates a Pair object from the objects on both sides.
/**
* Infix function declared with infix
*
* Extends Int by adding the multiply() function.
*/
infix fun Int.multiply(x: Int): Int {
return this * x
}
fun main() {
// Normal expression
val multiply1 = 3.multiply(10)
println("multiply1: $multiply1")
// Infix expression
val multiply2 = 3 multiply 10
println("multiply2: $multiply2")
}
Output:
multiply1: 30
multiply2: 30