Let’s take a look at operator overloading example in Kotlin (OperatorOverloading.kt):
class OvrldExmpl(var value: String) {
operator fun plus(toAdd: OvrldExmpl): OvrldExmpl {
return OvrldExmpl(value + ", " + toAdd.value)
}
}
fun operatorOverloadingExample() {
val a = OvrldExmpl("One")
val b = OvrldExmpl("Two")
val c = OvrldExmpl("Three")
val d = a + b
val e = a + b + c
println("A: ${a.value}")
println("B: ${b.value}")
println("C: ${c.value}")
println("D: ${d.value}")
println("E: ${e.value}")
}
Console output:
A: One
B: Two
C: Three
D: One, Two
E: One, Two, Three
We defined plus operation for our class using modifier operator for the function that has appropriate name.
Here is the list of pairs expression name to operator function name:
+a → a.unaryPlus()
-a → a.unaryMinus()
!a → a.not()
a++ → a.inc()
a-- → a.dec()
a + b → a.plus(b)
a – b → a.minus(b)
a * b → a.times(b)
a / b → a.div(b)
a % b → a.mod(b)
a in b → b.contains(a)
a !in b → !b.contains(a)
a[i] → a.get(i)
a[i, j] → a.get(i, j)
a[i_1, …, i_n] → a.get(i_1, …, i_n)
a[i] = b → a.set(i, b)
a[i, j] = b → a.set(i, j, b)
a[i_1, …, i_n] = b → a.set(a_1, …, a_n, b)
a() → a.invoke()
a(i) → a.invoke(i)
a(i_1, …, a_n) → a.invoke(a_1, …, a_n)
a+=b → a.plusAssign(b)
a-=b → a.minusAssign(b)
a*=b → a.timesAssign(b)
a == b → a?.equals(b) ?: b === null
a !=b → !(a?.equals(b) ?: b ===null)
a>b → a.compareTo(b) > 0
a<b → a.compareTo(b) < 0
a>=b → a.compareTo(b) >= 0
a<=b → a.compareTo(b) <= 0