Middle
What is operator overloading and how to use it?
sobes.tech AI
Answer from AI
Operator overloading in Kotlin allows you to define or override the behavior of standard operators (e.g., +, -, *, /) for user-defined data types.
It is used by defining special member functions or extension functions with fixed names, marked with the keyword operator.
Functions for operator overloading:
| Operator | Function name |
|---|---|
+ |
plus |
- |
minus |
* |
times |
/ |
div |
% |
rem, mod |
.. |
rangeTo |
in |
contains |
== |
equals |
!= |
equals (inverted result) |
< |
compareTo |
> |
compareTo |
<= |
compareTo |
>= |
compareTo |
[] |
get, set |
() |
invoke |
a += b |
plusAssign |
a -= b |
minusAssign |
a *= b |
timesAssign |
a /= b |
divAssign |
a %= b |
remAssign, modAssign |
+a |
unaryPlus |
-a |
unaryMinus |
!a |
not |
a++, ++a |
inc |
a--, --a |
dec |
Example of overloading the + operator for the Vector class:
data class Vector(val x: Int, val y: Int) {
// Overloading the "+" operator
operator fun plus(other: Vector): Vector {
return Vector(x + other.x, y + other.y)
}
}
fun main() {
val v1 = Vector(1, 2)
val v2 = Vector(3, 4)
val v3 = v1 + v2 // Using the overloaded operator
println(v3) // Output: Vector(x=4, y=6)
}
Example of overloading the [] (get) operator for a collection class:
class MyContainer(private val elements: List<String>) {
// Overloading the "[]" (get) operator
operator fun get(index: Int): String {
return elements[index]
}
}
fun main() {
val container = MyContainer(listOf("A", "B", "C"))
val element = container[1] // Using the overloaded operator
println(element) // Output: B
}