Operator overloading
Kotlin supports overloading existing operators (like +
, -
,+ =
, …).
To do this, it introduces the operator
keyword that makes possible overloads like this:
class Vector {
// ...
operator fun plus(vector: Vector) : Vector = Vector(this.x + vector.x, this.y + vector.y, this.z + vector.z)
}
With operator
we indicate that we want to overload one.
This is followed by a syntactically ordinary function declaration.
The name of the function indicates, which one of the operators you want to overload (plus
, minus
, div
, …), which also determines the rest of the signature.
For example, if it is a unary operator such as unaryMinus
, the function may not take any further arguments.
For binary operators, there is exactly one argument - the “right-hand side”.
The example above is the binary plus operator +
which allows you to add two instances of the Vector
class as follows:
val a = Vec(1,2,3)
val b = Vec(4,5,6)
val c = a + b // calling the overloaded plus operator
b
in the example, while a
maps to this
.
As a result, the function returns a new vector which corresponds to the addition of this
and the vector passed.Available operators
For a list of all overloadable operators and more information, see the official operator overloading documentation.
Useful overloads
The Kotlin standard library also makes heavy use of operator overloading and provides (in conjunction with corresponding extension functions) a lot of “syntactic sugar”.
For example, thanks to the overloaded +=
operator, you can add new items to a list as follows:
stringList += "Hello World!"
// instead of
stringList.add("Hello World!")
I also like the following way to access the elements of a map
:
map["Hello"] = "World!"
// or
val person = personsDatabase[42]