Signup/Sign In

Kotlin Operator Overloading

In this tutorial we will learn Operator Overloading in Kotlin. Each operator we use like +, -, ++ etc translates to a function under the hood. For example, following arithmetic functions translates to:

Operator Expression Underlying Function
+ a + b a.plus(b)
- a - b a.minus(b)
* a * b a.times(b)
/ a / b a.div(b)

Also, all these functions might also be overloaded for different data types. For example, plus() functions adds two numbers for Int type and concatenates two strings for String type.

Kotlin Operator Overloading

Operator overloading can be done by overloading the underlying function for that operator. It means to overload + operator, we should overload plus() function.

Let us create a class ComplexNumber and overload + operator for it. We will use operator keyword for overloading it:

class ComplexNumber(var real: Int, var imaginary: Int){
    // Operator Overloading
    operator fun plus(c: ComplexNumber): ComplexNumber{
        return ComplexNumber(this.real + c.real, this.imaginary + c.imaginary)
    }

    override fun toString(): String {
        return "${this.real} + ${this.imaginary}i"
    }
}

fun main() {
    val c1 = ComplexNumber(2,4)
    val c2 = ComplexNumber(3,3)
    println("Complex no. obtained by adding c1 & c2: ${c1.plus(c2)}")
}


Complex no. obtained by adding c1 & c2: 5 + 7i

In this example we have overloaded the plus() function to add two complex numbers. It will add real and imaginary parts to complex numbers.

Summary

In this tutorial we discussed about operator overloading and see one example. With this we come to the end of this Kotlin tutorial series. For references you can always refer to the official documentation:



About the author:
I'm a writer at studytonight.com.