The ‘infix‘ keyword in Kotlin is used to define functions that can be called using infix notation. Infix notation is a convenient way to call a function with two arguments without using the traditional method call syntax with parentheses and a dot.
To define an infix function, we must use the ‘infix‘ modifier before the function keyword. This enables the function to be called using infix notation.
Here is an example of an infix function in Kotlin:
infix fun Int.add(x: Int): Int {
return this + x
}
This function adds two integers and returns the result. Because it is marked as ‘infix‘, we can call it using infix notation like this:
val sum = 4 add 5
In this example, ‘4‘ is the left operand and ‘5‘ is the right operand. The ‘add‘ function is called using infix notation, and the result is assigned to the ‘sum‘ variable.
Note that with infix functions, the ‘this‘ keyword refers to the left operand, and the right operand is passed as a parameter. This makes the code more concise and readable.
Infix functions can also be used with other operators like ‘and‘, ‘or‘, ‘==‘, and ‘!=‘. Here is an example of using an infix function with the ‘and‘ operator:
infix fun Boolean.and(x: Boolean): Boolean {
return this && x
}
val result = true and false
In this example, we define an infix function called ‘and‘ that takes a boolean parameter and returns the logical AND of the left and right operands. We then use this function with infix notation to perform a logical AND operation between ‘true‘ and ‘false‘. The result is assigned to the ‘result‘ variable.