The fun of Kotlin — Infix Functions

The fun of Kotlin — Infix Functions

In the previous part of this series, we learned about Local functions in Kotlin. In this part, I’d like to talk about Infix functions. Infix notation makes function calls look super awesome.

Topics We'll Cover

  1. Local functions

  2. Infix functions (you’re here)

  3. Anonymous functions

  4. Inline functions

  5. Returns and local returns

Who Is This For?

This series is designed for all Kotlin enthusiasts, including those who are currently learning or have an interest in learning Kotlin.

Prerequisite

Before proceeding, I recommend you familiarize yourself with the basic syntax of the Kotlin language, such as how to define variables, classes, and functions. The official Kotlin website is an excellent place to start.

Infix functions

Functions marked with the infix keyword can also be called using the infix notation (omitting the dot and the parentheses for the call). Infix functions must satisfy the following requirements:

Examples of infix functions

Mathematical Operation Example

Infix functions can make mathematical operations more readable. Here's an example:

infix fun Int.pow(exponent: Int): Int {
    var result = 1
    for (i in 1..exponent) {
        result *= this
    }
    return result
}

// Usage:
val result = 2 pow 3  // equivalent to 2.pow(3)
println(result)  // Output: 8

This example shows how you can use infix notation to create a power function.

Domain-Specific Language (DSL) Example

Infix functions are often used to build domain-specific languages in Kotlin. Here's an example:

data class Pair(val a: Int, val b: Int)

infix fun Int.to(that: Int): Pair = Pair(this, that)

// Usage:
val pair = 1 to 2  // equivalent to 1.to(2)
println(pair)  // Output: Pair(a=1, b=2)

This example is a simplified version of the to function that is used to create pairs in Kotlin.

Inappropriate Usage

Infix functions should not be used when the function name doesn't convey its purpose:

// Confusing usage - it's not clear what the function does without looking at its implementation
infix fun Int.fancyOperation(other: Int) = this + other * 2

Example — Kotlin test framework

I think the best use case for infix notation is to make argument matchers in testing frameworks more readable and create nice-looking APIs.

kotlintest/kotlintest

Kotlintest is a testing framework for Kotlin. It uses infix notation extensively to make nice-looking APIs. Here is a snippet of their API.

Clean API of KotlinTest using infix notation

"substring" should include("str")

user.email should beLowerCase()

a + b shouldBe result

Further Reading

Official documentation of Infix notation

Check out more examples of Kotlin functions in my sample GitHub project.

jdsingh/kotlin-functions-examples


Thank you for taking the time to read this article. If you have any questions, or suggestions on how to improve this article, please feel free to contact me on Twitter :)

Jagdeep Singh