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
operator fun plusmakesLoad(11.5) + Load(6.2)compile.infix fun String.leadsallows"Rae" leads "Sam"— no dot, no parens.- Both are ordinary functions; the keywords only unlock the call syntax.
Keywords and builtins used here
DoubleLoadStringclassdatafuninfixleadsmainoperatorplusval
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.
Step 3 of 3 in Idioms, step 21 of 27 in Language basics.