Infix notation in Kotlin

  • Amit Shekhar
    Amit Shekhar
    Published on
Infix notation in Kotlin

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about the Infix notation in Kotlin. The Infix notation enables us to write code that looks much more like a natural language.

What is Infix notation in Kotlin?

Infix notation in Kotlin allows a function to be called without the use of the dot and parentheses.

We will understand this with an example.

Let's create a function add and mark it with the infix keyword as below:

infix fun Int.add(value: Int): Int = this + value

As we have read above that the functions marked with the infix keyword can also be called using the infix notation. It means that we can omit the dot and the parentheses.

This is how we can call this using infix notation.

val sum = 5 add 10

Now, the code looks much more like a natural language.

And I am sure that, you must have used somewhere like below in your Kotlin code earlier.

val map = mapOf(
    1 to "Amit Shekhar",
    2 to "Anand Gaurav",
    3 to "Lionel Messi"

mapOf needs the list of pairs: Pair<K, V>.

Here to for the Pair is possible only because of the infix.

When we check the source code of the Pair in Kotlin, we will find the following.

infix fun <A, B> B): Pair<A, B> = Pair(this, that)

This is why we are able to create Pair using infix notation.

Now, it is also important to know about the precedence of the Infix function calls.

  • Infix function calls have lower precedence than arithmetic operators. It means that 5 add 10 + 15 is equivalent to 5 add (10 + 15)
  • Infix function calls have higher precedence than the boolean operators && and ||. It means that a && b xor c is equivalent to a && (b xor c).

Rules that we need to follow while creating Infix functions:

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

The following are NOT correct as they are not following the above rules.

  • Have more than one parameter.
infix fun Int.add(a: Int, b: Int): Int // WRONG
  • Have a variable number of arguments.
infix fun Int.add(vararg numbers: Int): Int // WRONG
  • Have a default value for the parameter.
infix fun Int.add(value: Int = 10): Int // WRONG

So, we need to keep the rules in mind while creating them. This is how we can use infix notation in Kotlin.

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.


Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.