[Kotlin] What is Infix Functions?
GOAL
To understand infix functions in Kotlin.
What is infix function?
In Kotlin, functions marked with the infix keyword can also be called using the infix notation (sited from the documentation of Kotlin). An example follows.
infix fun Int.add(a:Int): Int { return this+a }
What is infix notation?
Infix notation is one of the notation types. In infix notation the operator is described in thee middle of the targets. + – * / are usually used as infix notation. (1+2, a-b)
- Infix notation
- (1+2)*(3-4)
- Prefix notation (Polish notation)
- *+12-34
- Postfix notation (Reverse Polish notation)
- 12+34-*
Implementation in Kotlin
fun pre_add(a:Int, b:Int): Int{ return a+b } infix fun Int.in_add(a:Int): Int { return this+a } infix fun Int.in_sub(a:Int): Int = this-a fun main() { println(pre_add(1,2)) println(1 in_add 2) println(1.in_add(2)) println(1 in_sub 2) println(1.in_sub(2)) }
output
3 3 3 -1 -1