Operator Overloading
Kotlin allows you to provide custom implementations for the predefined set of operators on types.
To implement an operator, provide a member function or an extension function with a specific name for the corresponding type.
To overload an operator, mark the corresponding function with the operator modifier:
When overriding your operator overloads, you can omit operator:
Unary operations
Unary prefix operators
Expression | Translated to |
|---|---|
|
|
|
|
|
|
Increments and decrements
Expression | Translated to |
|---|---|
|
|
|
|
The compiler performs the following steps for resolution of an operator in the postfix form, for example a++:
Store the initial value of
ato a temporary storagea0.Assign the result of
a0.inc()toa.Return
a0as the result of the expression.
For the prefix forms ++a, the effect is:
Assign the result of
a.inc()toa.Return the new value of
aas a result of the expression.
Binary operations
Arithmetic operators
Expression | Translated to |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
For the operations in this table, the compiler just resolves the expression in the Translated to column.
Below is an example Counter class that starts at a given value and can be incremented using the overloaded + operator:
in operator
Expression | Translated to |
|---|---|
|
|
|
|
For in and !in the procedure is the same, but the order of arguments is reversed.
Indexed access operator
Expression | Translated to |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
invoke operator
Expression | Translated to |
|---|---|
|
|
|
|
|
|
|
|
Augmented assignments
Expression | Translated to |
|---|---|
a += b | a.plusAssign(b) |
a -= b | a.minusAssign(b) |
a *= b | a.timesAssign(b) |
a /= b | a.divAssign(b) |
a %= b | a.remAssign(b) |
Equality and inequality operators
Expression | Translated to |
|---|---|
|
|
|
|
The == operation is special: it is translated to a complex expression that screens for null's.
If both things are
null,==will returntrue.If one thing is
nulland the other isn't,==will returnfalsewithout calling theequals()method on the non-null object.
This way, you don't have to worry about getting an error when comparing something to null.
Comparison operators
Expression | Translated to |
|---|---|
|
|
|
|
|
|
|
|
All comparisons are translated into calls to compareTo, that is required to return Int.