Kotlin

Infix Functions

admin by @admin ADMIN
13m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
A single-arg method/extension can be called without dot or parens when marked `infix`. Lets you write DSL-style code like `5 shouldBe 5` or `key to value`.
Kotlin
Raw
// Stdlib examples: `to`, `until`, `step`, `downTo`, `xor`, `or`, `and`
fun main() {
    val pair = "name" to "Alice"               // infix `to`
    for (i in 1 until 5) print(i)              // 1234   (infix `until`)
    for (i in 1..10 step 2) print(i)           // 13579  (infix `step`)
    println()

    // Custom infix
    infix fun Int.shouldBe(expected: Int) {
        require(this == expected) { "expected $expected but got $this" }
    }
    (2 + 2) shouldBe 4                          // reads naturally

    // Custom infix on classes (must be a member function or extension)
    infix fun String.containing(other: String): Boolean = contains(other)
    println("hello world" containing "world")   // true
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.