Operators and Operator Overloading in Kotlin
Kotlin provides a rich set of built-in operators and allows operator overloading, making code with custom types concise and natural.
Built-in Operators
- Arithmetic —
+ - * / % - Compound assignment —
+= -= *= /= %= - Comparison —
== != < > <= >= - Logical —
&& || ! - Bitwise —
shl shr ushr and or xor inv - Range & progression —
.. until downTo step - Membership —
in !in - Identity —
=== !== - Null safety —
?.(safe call),?:(Elvis),!!(not-null assertion) - Indexing & invocation —
[]→get/set,()→invoke
Everyday Examples
val a = 15
val b = 4
println(a + b) // 19
println(a % b) // 3
println(a in 1..20) // true
val name: String? = null
val display = name ?: "Guest"
println(display) // Guest
Operator Overloading
Any class can define custom behavior for operators by declaring member or extension functions marked with the operator keyword.
1. Overloading +
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}
val p1 = Point(1, 2)
val p2 = Point(3, 4)
println(p1 + p2) // Point(x=4, y=6)
2. Overloading indexing []
class Board {
private val cells = Array(9) { ' ' }
operator fun get(index: Int) = cells[index]
operator fun set(index: Int, value: Char) {
cells[index] = value
}
}
val board = Board()
board[0] = 'X'
println(board[0]) // X
3. Overloading invocation ()
class Greeter(val greeting: String) {
operator fun invoke(name: String) = println("$greeting, $name!")
}
val hi = Greeter("Hi")
hi("Kotlin") // Hi, Kotlin!
Common Overloadable Operators
| Operator | Required function name |
|---|---|
+ - * / % | plus, minus, times, div, rem |
+= -= etc. | plusAssign, minusAssign … |
== != | equals (data classes do it automatically) |
< > <= >= | compareTo |
[] | get / set |
() | invoke |
in !in | contains |
.. | rangeTo |