Infix functions in Kotlin

Tarun Chawla
2 min readApr 19, 2019

Functions marked as infix are called infix functions. They can be called using infix notation. The infix notation is a way of calling the function without ‘.’ and ‘()’. On the left side, you will place the receiver instance and on the right side, you will place the parameter.

infix fun Int.plus(a : Int) : Int{
return this + a;
}
fun main(){
println("1 plus 5 is: ${1 plus 5}")
println("1 plus 5 using regular invocation is : ${1.plus(5)}")
}

Infix function must satisfy the following requirements:

  1. They must be member functions or extension functions.
  2. They must have single parameter and it should not accept variable arguments and must not have default value.

Infix calls have lower precedence over arithmetic operators, type casts and rangeTo operators. The following expressions are equivalent.

  • 1 plus 2 + 3 and 1 plus (2 + 3)
  • 0 until n * 2 and 0 until (n * 2)
  • xs union ys as Set<> and xs union (ys as Set<>)

On the other hand, infix function call’s precedence is higher than that of the boolean operators && and ||, is- and in-checks, and some other operators. These expressions are equivalent as well, here xor is Kotkin’s infix function:

  • a && b xor c and a && (b xor c)
  • a xor b in c and (a xor b) in c

Infix notation always require both receiver and parameter to be specified. Use this explicitly when you are calling method in receiver class.

class Infix(value : Int) {
val Val: Int = value
infix fun plus(a : Int) = this.Val + a
fun callInfix(){
this plus 5 //Correct, both receiver and parameter are specified while calling via infix notation
plus 5 //Incorrect, receiver is not specified
plus(5) //Correct, regular function invocation and this is auto implied.
}
}

--

--