Skip to content

Koltin infix Notation

by: Parshav

Posted on:December 24, 2021 at 08:24 PM

Kotlin infix notation

What does it do


The infix keyword can be applied to kotlin functions. This simply allows it to be called without requiring parenthesis for its parameter.


Here’s a small example with a Player that can hold a card at any given time. The player can swapCard if the other card’s value is greater than the one they hold. We apply the infix notation to the swapCard function.

class Player(card: Card) {

    var card: Card = card
        private set

    infix fun swapCard(other: Card) {
        if (other.value > card.value) {
            card = other
        }
    }
    
    override fun toString(): String {
        return "Player Card :: ${card.value}"
    }
}

data class Card(val value: Int)

Lets try swapping a players card

@Test
fun `test swap`() {
    val purplePlayer = Player(Card(4))

    purplePlayer swapCard Card(6)

    println(purplePlayer) // successful swap 
    // prints Player Card :: 6

    purplePlayer swapCard Card(5) //unsuccessful swap
    // prints Player Card :: 6

    println(purplePlayer)
}

We’re able to call the swapCard function without using the parenthesis.


Constriants


Only a single parameter can be passed into them.

class Player (...) {
    ...
    infix fun swapTwo(other: Card, cardB: Card) { ... } // will NOT compile
    ...	
}

Usage in standard library


Infix functions are already used within the standard Kotlin library as well. until returns a range from the provided lower and upper bound.

@Test
fun `range demonstration`() {
    (0 until 10).forEach {
        print(it)
    }
}
// prints 0123456789

Another common usage is the to infix function when adding elements to a map.

@Test
fun `map to demonstration`() {
    val dummyMap = mapOf(
        "One" to 1,
        "Two" to 2
    )
    dummyMap.forEach { (k, v) ->
        print("$k $v ")
    }
}
// prints One 1 Two 2