Infix notation in function
Another Kotlin treasure that I have not known is the ability to write infix notation in function. We use infix notation in most arithmetic operation such as a + b
. The infix notation is where the operator (+
) is used between the operands (a
) and (b
). In infix notation, only functions defined using the infix
keyword can be called this way.
There are 3 things to make this infix
notation.
- They must be member functions or extension functions.
- They must have a single parameter.
- The parameter must not accept variable number of arguments and must have no default value.
class MyStringCollection {
infix fun add(s: String) { /*...*/ }
fun build() {
this add "abc" // Correct
add("abc") // Correct
//add "abc" // Incorrect: the receiver must be specified
}
}