Blog / October 26, 2020 / 2 mins read / By Suneet Agrawal

Infix Notation : Kotlin

Ever imagined calling a public function of a class without dot and parentheses of the parameter in Kotlin. Kotlin provides infix notation with which we can call a function with the class object without using a dot and parentheses across the parameter. Using infix function provides more readability to a function similar to other operators like in, is, as in Kotlin.

To make a function infix notation enabled, add infix keyword before the function.

infix fun Int.add(b : Int) : Int = this + b
val x = 10.add(20)
val y = 10 add 20        // infix call

But an Infix function must satisfy the following requirements

  • They must be member functions or extension functions.
  • They must have a single parameter.
  • The parameter must not accept a variable number of arguments and must have no default value.

What if I use an infix function with other operators.

You can but you should keep the priority of the operator in mind. Infix function calls have lower precedence than the arithmetic operators, type casts, and the rangeTo operator. For example

  • 1 add 2 + 3 is equivalent to 1 add (2 + 3)
  • 0 until n * 2 is equivalent to 0 until (n * 2)
  • xs union ys as Set<> is equivalent to 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. For example

  • a && b xor c is equivalent to a && (b xor c)
  • a xor b in c is equivalent to (a xor b) in c

But infix functions always require both the receiver and the parameter to be specified. When you are calling a method on the current receiver using the infix notation, you need to use this explicitly. Unlike a regular method call, this cannot be omitted. This is required to ensure unambiguous parsing.

class StringCollection {

    infix fun add(s: String) {
        // perform some action here
    }

    fun build() {
        this add "abc"   // Works fine, calls the infix function
        add("abc")       // Works fine, note this is not an infix call
        add "abc"       // error: the receiver must be specified
    }
}
Comments