March 3, 2023

How to Use Infix Notation in Kotlin Programming Language.

Learn about the use of infix notation in Kotlin programming language with this tutorial. Discover how to define infix functions and call them using a special syntax.

Kotlin is a programming language that runs on the Java Virtual Machine (JVM). It is an open-source language developed by JetBrains. One of the interesting features of Kotlin is infix notation. Infix notation allows you to call a function on an object using a special syntax that makes it more natural to read and write code. In this tutorial, we will learn about infix notation in Kotlin.

What is infix notation in Kotlin?

Infix notation is a feature of Kotlin that allows you to call a function on an object using a special syntax. Normally, you would call a function using dot notation, like this:


val result = obj.function(argument)

In infix notation, you can call the same function like this:


val result = obj function argument

The infix notation uses a single space between the object and the function name, and between the function name and the argument.

How to define an infix function in Kotlin?

To use the infix notation, you need to define a function as infix. You can do this by using the infix keyword before the function declaration.


infix fun functionName(argument: ArgumentType): ReturnType {   // function body }

For example, let's define an infix function that adds two integers:


infix fun Int.add(other: Int): Int {   return this + other }

In this example, we have defined an infix function add that takes another integer as an argument and returns the sum of the two integers.

How to use infix functions in Kotlin?

Once you have defined an infix function, you can call it using infix notation. For example, let's use the add function that we defined earlier:


val result = 3 add 5

In this example, we are calling the add function on the integer 3 using infix notation. We are passing the integer 5 as the argument to the add function. The result variable will contain the value 8.

Rules for using infix functions in Kotlin

There are some rules that you need to follow when using infix functions in Kotlin:

  1. The function must be a member function or an extension function.
  2. The function must have a single parameter.
  3. The function must be marked as infix using the infix keyword.
  4. The function name must be a valid identifier.
  5. The function must not be a vararg function.


Infix notation is a powerful feature of Kotlin that makes code more readable and natural. By using infix functions, you can call functions on objects using a more intuitive syntax. Infix functions are easy to define and use, and they can make your code more concise and expressive.

Last edited on March 3, 2023 by Admin

Latest articles