Operator Overloading in Simplest way

Glitch
2 min readJun 25, 2021

When we work with types that can be added, removed, compared, or concatenated we end up with verbose code that we need to write again and again. In Kotlin, we can write more expressive and concise code for these types with the help of operator overloading.

What is Operator OverLoading?

The concept of operator overloading provides a way to invoke functions to perform the arithmetic operation, equality checks, or comparison on whatever object we want, through symbols like +, -, /, *, %, <, >. But, obviously, those overloading should be defined when it makes sense to use them.

For the following parts, let’s assume we have the data class:

data class Point(val x: Double, val y: Double)

Arithmetic operators

To overload the + operator we need to implement the function plus, with the keyword operator. This function takes one parameter of any kind, even it makes sense in most cases to use the same type.

// Here how to provide `+` operator on our object Point
operator fun plus(p: Point) = Point(this.x + p.x, this.y + p.x)
// return type is inferred to Point

To go further we can apply all the following operator overloading on the object Point.

EXPRESSIONFUNCTION CALLED

p1 + p2 | p1.plus(p2)

p1 - p2 | p1.minus(p2)

p1 * p2 | p1.times(p2)

p1 / p2 | p1.div(p2)

p1 % p2 | p1.rem(p2)

p1++ | p1.inc()

p1-- | p1.dec()

Kotlin program to demonstrate the operator overloading –

class IncDecOverload(var str:String) {
// overloading increment function
operator fun inc(): IncDecOverload {
val obj = IncDecOverload(this.str)
obj.str = obj.str + 'a'
return obj
}
// overloading decrement function
operator fun dec(): IncDecOverload {
val obj = IncDecOverload(this.str)
obj.str = obj.str.substring(0,obj.str.length-1)
return obj
}

override fun toString(): String {
return str
}
}
// main function
fun main(args: Array<String>) {
var obj = IncDecOverload("Hello")
println(obj++)
println(obj--)
println(++obj)
println(--obj)
}

Output:

Hello
Helloa
Helloa
Hello

That was a small but important concept to be. Keep Coding !!

--

--