The Analogy: The Pipe Organ Console
A pipe organ console presents a universal vocabulary. Any organist who sits down recognises the manuals, the pedalboard, the stops -- the layout and the symbols are the same the world over, so a player reads them instantly without instruction. Yet which pipes each key actually sounds is decided entirely by how the builder connected the trackers behind the console. The console is a shared language; the voice behind it is the builder's own. Kotlin operator overloading works exactly this way: the symbols +, -, [], (), in, and .. are a fixed, universal vocabulary, and you decide what each one does for your own type by wiring it to a function.
The wiring is not free-form. Each control on the console connects only to a tracker bar bearing a specific, fixed name -- the great-manual bar, the swell bar, the pedal bar -- and you cannot invent a new label and expect the key to find it. Kotlin imposes the same discipline: each operator maps to a function with a fixed conventional name. The plus sign routes to plus, square brackets to get and set, parentheses to invoke, the in keyword to contains, and the range dots to rangeTo. And just as a tracker must be physically connected before a key does anything, the function must be marked with the operator keyword before the symbol is wired to it.
The universal vocabulary is both the point and the peril. Because every organist already knows what a key is supposed to mean -- low keys sound low, the swell pedal swells -- the builder owes them that consistency, and an organ wired faithfully can be played on sight. The same debt applies in code: a + b should combine, a[i] should index into something, a in b should test membership. Operators arrive pre-loaded with reader expectations, so overloading one is a promise that your type will behave the way the symbol universally reads. Honour the promise and your type slots into the language as if it had always belonged.
The failure comes in two shapes. The first is the builder who labels a tracker add where the console expects plus, or who never connects the tracker at all -- the key then sounds nothing, because the console only drives trackers of the exact expected name that are actually wired. In Kotlin, using a non-convention name or omitting the operator keyword leaves you with an ordinary method that no symbol invokes. The second, worse shape is the builder who wires the swell pedal to cut the wind instead: + made to subtract, to mutate in place, or to fire an unrelated side effect. The organ still plays and the code still compiles, but every reader is misled, because operator overloading spends borrowed familiarity, and wiring a symbol against its universal meaning spends that familiarity on confusion.
Syntax or Core Structure
An operator is a normal function marked operator with a conventional name. Declaring plus wires the + symbol to it; the function returns the combined value.
data class Vec(val x: Int, val y: Int) {
operator fun plus(other: Vec): Vec = Vec(x + other.x, y + other.y)
operator fun times(factor: Int): Vec = Vec(x * factor, y * factor)
}
fun main() {
val a = Vec(1, 2)
val b = Vec(3, 4)
println(a + b)
println(a * 3)
}
Output:
Vec(x=4, y=6)
Vec(x=3, y=6)
Vec declares plus, so a + b compiles to a.plus(b) and returns a new Vec(4, 6) -- the compiler rewrites the symbol into the conventional call. times wires the * symbol, so a * 3 becomes a.times(3) and scales the vector to Vec(3, 6). Because Vec is a data class, its generated toString prints the Vec(x=..., y=...) form you see. Both operators return new values rather than mutating a, which matches what a reader expects + and * to do.
Technical Depth: The Convention Table and Common Operators
Symbol to function name
Each operator symbol is rewritten by the compiler into a call to a fixed-name function. The table lists the common ones.
| Symbol | Function | Kind |
|---|---|---|
a + b | a.plus(b) | binary arithmetic |
a - b | a.minus(b) | binary arithmetic |
a * b | a.times(b) | binary arithmetic |
a[i] | a.get(i) | indexed access |
a[i] = v | a.set(i, v) | indexed assignment |
a(x) | a.invoke(x) | call |
x in a | a.contains(x) | membership |
a..b | a.rangeTo(b) | range |
a < b | a.compareTo(b) < 0 | comparison |
a += b | a.plusAssign(b) or a = a.plus(b) | augmented |
Comparison operators all route through a single compareTo, and == routes through equals. You cannot invent new symbols; you can only give meaning to the existing set.
Indexed access with get and set
Defining get and set lets an object be indexed with square brackets like a collection.
class Grid(val cols: Int) {
private val cells = IntArray(cols * cols)
operator fun get(r: Int, c: Int): Int = cells[r * cols + c]
operator fun set(r: Int, c: Int, value: Int) { cells[r * cols + c] = value }
}
fun main() {
val g = Grid(3)
g[1, 2] = 9
println(g[1, 2])
println(g[0, 0])
}
Output:
9
0
get and set can take multiple indices, so g[1, 2] maps to g.get(1, 2) and g[1, 2] = 9 maps to g.set(1, 2, 9). Writing 9 at row 1, column 2 stores it at the flattened offset, and reading the same cell returns 9. An untouched cell like g[0, 0] is still 0 from the array's default. The two-dimensional bracket syntax reads naturally even though the storage underneath is a flat array.
Calling an instance with invoke
Defining invoke makes an instance callable with parentheses, like a function object.
class Multiplier(private val factor: Int) {
operator fun invoke(n: Int): Int = n * factor
}
fun main() {
val triple = Multiplier(3)
println(triple(5))
println(triple(10))
}
Output:
15
30
Because Multiplier defines invoke, the expression triple(5) is rewritten to triple.invoke(5), returning 5 times the stored factor, 15. Calling triple(10) gives 30. The object behaves syntactically like a function while remaining a full object with state -- the factor it was built with.
Membership with contains
Defining contains wires the in keyword, letting you ask whether a value belongs.
class Span(val lo: Int, val hi: Int) {
operator fun contains(n: Int): Boolean = n in lo..hi
}
fun main() {
val s = Span(10, 20)
println(15 in s)
println(25 in s)
}
Output:
true
false
The expression 15 in s is rewritten to s.contains(15), which checks whether 15 falls within 10 to 20 -- it does, so the result is true. 25 in s is false because 25 is above the upper bound. The operand order matters: x in a always calls a.contains(x), so the collection-like object is the receiver even though it is written on the right.
Ordering through compareTo
Implementing Comparable with a single compareTo wires all four comparison operators at once and gives the type a natural order that sorting uses.
class Version(val major: Int, val minor: Int) : Comparable<Version> {
override fun compareTo(other: Version): Int =
if (major != other.major) major - other.major
else minor - other.minor
override fun toString(): String = major.toString() + "." + minor
}
fun main() {
val list = listOf(Version(1, 4), Version(1, 2), Version(2, 0))
println(list.sorted())
println(Version(1, 4) > Version(1, 2))
}
Output:
[1.2, 1.4, 2.0]
true
compareTo returns a negative, zero, or positive number, and every comparison operator is defined in terms of its sign -- a > b means a.compareTo(b) > 0. Sorting compares major versions first and falls back to minor, so the list orders as 1.2, 1.4, 2.0. The direct comparison Version(1, 4) > Version(1, 2) is true because the majors tie and 4 exceeds 2. Implementing one function gave the type a complete, consistent ordering rather than four separate operators to keep in sync.
Unary and increment operators
Single-operand symbols have conventions too: unaryMinus wires the prefix -, and inc wires ++. Like their binary cousins, they should return new values.
data class Cell(val n: Int) {
operator fun unaryMinus(): Cell = Cell(-n)
operator fun inc(): Cell = Cell(n + 1)
}
fun main() {
var c = Cell(5)
println(-c)
c++
println(c)
}
Output:
Cell(n=-5)
Cell(n=6)
The prefix -c routes to c.unaryMinus(), producing Cell(-5) without touching c. The c++ form calls c.inc() and reassigns the result back into the var, so c becomes Cell(6); because inc returns a fresh Cell rather than mutating, the variable is rebound rather than the object changed. This is why inc must be applied to a var -- the operator produces a new value that the compiler stores back into the binding.
Real World Example: A Balance That Adds
A ledger app models an account Balance and wants natural arithmetic: account + deposit should give the balance after a deposit. The author overloads plus, but writes it to update the account in place and return it -- a small shortcut that seems to save an allocation.
class Balance(var cents: Int) {
// shortcut: mutate this and return it, instead of a new Balance
operator fun plus(deposit: Int): Balance {
cents += deposit
return this
}
override fun toString(): String = "Balance(" + cents + ")"
}
fun main() {
val opening = Balance(100)
val afterDeposit = opening + 50
println("afterDeposit = " + afterDeposit)
println("opening = " + opening)
println("same object = " + (afterDeposit === opening))
}
Output:
afterDeposit = Balance(150)
opening = Balance(150)
same object = true
The headline number looks right: after adding 50 to 100, afterDeposit reads Balance(150). If you only inspected that one line, the operator would appear to work perfectly, and a passing test that checks just afterDeposit would give false confidence.
The next two lines expose the damage. opening also reads Balance(150), even though the code never assigned to it after construction, and afterDeposit === opening is true -- they are the very same object. The overloaded + mutated the receiver and handed back a reference to it, so the "before" and "after" balances are one and the same, and the original opening figure has been silently destroyed.
This is the genuine design flaw, and it is a textbook operator abuse: + is universally read as a pure combination that yields a new value and leaves its operands untouched, exactly as 3 + 4 does not alter 3. Wiring it to mutate this betrays that expectation while still compiling and even producing the right headline number, which is what makes it dangerous. Any code that keeps a reference to a balance and then computes a new one via + will find its original corrupted, and expressions like a + b + c become order-dependent nonsense. The fix is to make plus return a fresh instance -- operator fun plus(deposit: Int) = Balance(cents + deposit) -- and, if in-place accumulation is genuinely wanted, to express that with plusAssign behind +=, whose name and syntax openly signal mutation. An operator's power is that readers already know what it means; the one thing you must not do is quietly mean something else.
Common Mistakes
- Making a binary operator mutate its receiver.
+,-, and*are read as pure combinations that return new values. Mutatingthisand returning it corrupts the operand and breaks chained expressions. Return a fresh instance.
- Forgetting the
operatorkeyword. A function namedpluswithoutoperatoris just a method; the+symbol will not route to it. The keyword is what wires the convention.
- Using a non-convention name. Only the fixed names (
plus,get,invoke,contains, and so on) are recognised. Naming a functionaddand expecting+to find it does not work.
- Overloading operators with surprising meaning. Wiring
+to divide, orinto mean something other than membership, compiles but misleads every reader. Overload only when the symbol's usual meaning fits.
- Breaking the
equals/hashCodecontract. Overridingequalswithout a matchinghashCodecorrupts hash-based collections. The two must agree: equal objects must share a hash code.
- Making
compareToinconsistent withequals. IfcompareToreturns 0 for objects thatequalssays are unequal, sorted sets and maps misbehave. Keep the natural ordering consistent with equality.
- Confusing
plusandplusAssignfor+=. If both exist for the same types,+=is ambiguous and fails to compile. Provideplusfor immutable types andplusAssignfor mutable ones, not both.
- Overloading
invokeon a type where a call reads as nonsense. Just because an object can be made callable does not mean it should be. Reserveinvokefor genuine function-like objects.
- Ignoring operand order for
in.x in aalways callsa.contains(x), notx.contains(a). Puttingcontainson the wrong type leavesinunwired.
Best Practices
- Overload an operator only when its universal meaning genuinely fits your type, so
a + bcombines anda[i]indexes as readers expect. - Return new values from arithmetic operators and leave operands unchanged; express in-place accumulation through
plusAssignand+=where mutation is explicit. - Prefer implementing
Comparableand its singlecompareToover hand-wiring individual comparison operators, and keep it consistent withequals. - Always pair an
equalsoverride with a matchinghashCodeso hash-based collections behave. - Use
get/setto expose collection-like indexing, taking multiple indices when the data is multi-dimensional. - Reserve
invokefor objects that are conceptually functions with captured state, not as a clever way to hide a method call. - Mark every convention function
operatorand use the exact convention name, since a wrong name or missing keyword silently leaves the symbol unwired. - Favour readability over cleverness: if an operator would surprise a reviewer, expose a named method instead.
Practice Exercises
- Give a
Moneyclass anoperator fun plusthat returns a newMoney, and confirm thata + bleaves bothaandbunchanged by printing all three.
- Implement
getandseton aMatrixclass backed by a flat array, and read and write cells with two-index bracket syntax.
- Reproduce the mutating-
plusflaw: writeplusto mutate and returnthis, show that the original operand is corrupted and that the two references are identical, then fix it to return a fresh instance.
- Make a class
Comparableby implementingcompareTo, then sort a list of its instances and confirm the ordering matches yourcompareTologic.