Kotlin

Operator Overloading

admin by @admin ADMIN
Jun 20, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Specially-named methods or extensions get operator syntax: `plus → +`, `minus → -`, `times → *`, `get → []`, `invoke → ()`, `contains → in`. Use sparingly for types that have natural arithmetic semantics.
Kotlin
Raw
data class Vec2(val x: Double, val y: Double) {
    operator fun plus(other: Vec2)   = Vec2(x + other.x, y + other.y)
    operator fun minus(other: Vec2)  = Vec2(x - other.x, y - other.y)
    operator fun times(scalar: Double) = Vec2(x * scalar, y * scalar)
    operator fun unaryMinus()        = Vec2(-x, -y)
}

class Inventory {
    private val items = mutableMapOf<String, Int>()
    operator fun get(sku: String) = items[sku] ?: 0
    operator fun set(sku: String, qty: Int) { items[sku] = qty }
    operator fun contains(sku: String) = sku in items
}

fun main() {
    val a = Vec2(1.0, 2.0)
    val b = Vec2(3.0, 4.0)
    println(a + b)               // Vec2(x=4.0, y=6.0)
    println(b - a)               // Vec2(x=2.0, y=2.0)
    println(a * 3.0)             // Vec2(x=3.0, y=6.0)
    println(-a)                  // Vec2(x=-1.0, y=-2.0)

    val inv = Inventory()
    inv["A1"] = 10               // calls set()
    println(inv["A1"])           // 10 — calls get()
    println("A1" in inv)         // true — calls contains()
}
Tags

Save your own code snippets

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