Kotlin Infix Function

Infix notation is the notation where an operator or function is placed between the operands or arguments.

Example

val direction = "East" to "West"

To define an infix function, place the infix keyword before the fun keyword.

The following requirements must be fulfill to make a function infix.

  • The function must be a member functions or extension functions.
  • They must have a single argument.
  • The parameter must not have default values or variable number of arguments.

Example

fun main(args : Array<String>)  {  
	val acc2 = InfixFunc()
    acc2 add 100.00
}
class InfixFunc {
    var balance = 10.0
    infix fun add(amount: Double): Unit {
        this.balance = balance + amount
        print(this.balance)
    }
}
Output
110.0

In the above example, we have called the function using infix notation, the calling of the function is same as -

account2 add(100.00)

Infix function calls have lower precedence than the arithmetic operators, type casts, and the rangeTo operator and its function call precedence is higher than that of the boolean operator && and ||, is- and in-checks.

Example

x && y xor z and x && (y xor z)
x xor y in z and (x xor y) in z

The above expressions are equivalent.









Read more articles