Kotlin Infix Function: In this tutorial, you will learn to use infix notation to call a function in Kotlin (with the assistance of examples).

Before you learn how to create a function having infix notation, let’s explore two commonly used infix functions.

At the point when you use || and && activities, the compiler look up for or and and works respectively, and calls them under the hood.

These two functions support infix notation.

Example: Kotlin or & and function

fun main(args: Array<String>) {
    val a = true
    val b = false
    var result: Boolean

    result = a or b // a.or(b)
    println("result = $result")

    result = a and b // a.and(b)
    println("result = $result")

At the point when you run the program, the output will be:

result = true
result = false

In the above program, a or b rather than a.or(b), and a and b rather than a.and(b) is used. It was conceivable on the grounds that these two functions support infix notation.

How to create a function with infix notation?

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

You can make a function call in Kotlin using infix notation if the function

  • is a member function (or an extension function).
  • has only one single parameter.
  • is marked with infix keyword.

Example: User-defined Function With Infix Notation

class Structure() {

    infix fun createPyramid(rows: Int) {
        var k = 0
        for (i in 1..rows) {
            k = 0
            for (space in 1..rows-i) {
                print("  ")
            while (k != 2*i-1) {
                print("* ")

fun main(args: Array<String>) {
    val p = Structure()
    p createPyramid 4       // p.createPyramid(4)

At the point when you run the program, the output will be:

    * * * 
  * * * * * 
* * * * * * * 

Here, createPyramid() is an infix work that creates a pyramid structure. It is a member function of class Structure, takes just a single parameter of type Int, and starts with catchphrase infix.

The quantity of rows the pyramind relies upon the argument passed to the function.

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.


Leave a Reply

Avatar placeholder