Skip to content
Justice Tech School

Operator Overloading

operator fun plus, minus, get and compareTo make types work with operators.

Example
data class V(val x: Int, val y: Int) {
    operator fun plus(o: V) = V(x + o.x, y + o.y)
}
println(V(1, 2) + V(3, 4))

Exercise

Overload plus.

operator fun (o: V)

Quiz Test

Which function does + call?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.