typestar

Operators and infix in Kotlin

Teach + a new type, or let a function sit between its operands.

data class Load(val kg: Double) {
    // operator fun teaches + a new operand pair.
    operator fun plus(other: Load) = Load(kg + other.kg)
}

// infix lets a one-argument function sit between its operands.
infix fun String.leads(follower: String) = "$this walks ahead of $follower"

fun main() {
    val total = Load(11.5) + Load(6.2)
    println("Carrying ${total.kg} kg")
    println("Rae" leads "Sam")
}

How it works

  1. operator fun plus makes Load(11.5) + Load(6.2) compile.
  2. infix fun String.leads allows "Rae" leads "Sam" — no dot, no parens.
  3. Both are ordinary functions; the keywords only unlock the call syntax.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
388
Tokens
89
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 3 of 3 in Idioms, step 21 of 27 in Language basics.

← Previous Next →