Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 15 / Topic 5 of 6

Operator conventions

a + b, a[i], a in b, a(), a > b aren't special-cased by the compiler for your own types -- each is a plain call to an operator fun with one fixed name. Write that function and your type gets to use the operator; there's no other magic.

You write Kotlin calls Name
a + b, a * b a.plus(b), a.times(b) plus, times, minus, div, rem
a > b, a < b a.compareTo(b) compareTo (from Comparable<T>)
a[i], a[i] = v a.get(i), a.set(i, v) get, set
v in a a.contains(v) contains
a(args) a.invoke(args) invoke
data class RupeesPaise(val paise: Long) : Comparable<RupeesPaise> {
    operator fun plus(other: RupeesPaise) = RupeesPaise(paise + other.paise)
    operator fun times(factor: Int) = RupeesPaise(paise * factor)
    override fun compareTo(other: RupeesPaise) = paise.compareTo(other.paise)
    override fun toString() = "Rs.%d.%02d".format(paise / 100, paise % 100)
}

class Cart(private val prices: MutableMap<String, RupeesPaise> = mutableMapOf()) {
    operator fun get(item: String): RupeesPaise? = prices[item]
    operator fun set(item: String, price: RupeesPaise) { prices[item] = price }
    operator fun contains(item: String) = item in prices
    operator fun invoke(): RupeesPaise =
        prices.values.fold(RupeesPaise(0)) { total, price -> total + price }
}
Rs.249.00
Rs.597.00
rice costlier than dal: true
Rs.199.00
rice in cart: true
ghee in cart: false
cart total: Rs.249.00

cart["rice"] = riceBag is exactly cart.set("rice", riceBag); "rice" in cart is exactly cart.contains("rice"); cart() is exactly cart.invoke(). Every one of them compiles to an ordinary invokevirtual on the method with that name -- confirm it yourself with javap -c on main the same way section 3 did for lambdas.

Full program: examples/05_operator_conventions.kt.

Done here? The practice set for Part 15 — including the solutions — is on the part page.

Search the guide