Kotlin Operator Overloading

Since Kotlin provides user-defined types, it also provides the additional functionality to overload the standard operators, so that working with user-defined types is easier. All of the unary, binary, relational operators can be overloaded. The operators are overloaded either through the member functions or through extension functions. These functions are preceded by the operator modifier. There are standard functions for every type of operator that can be overloaded according to the usage.

Unary Operators –

The following table shows the various functions that can be defined for unary operators. These functions modify the calling instance.

Operator expression Corresponding function
+x x.unaryPlus()
-x x.unaryMinus()
!x x.not()

Here, x corresponds to the type for which the operator is defined. The overloaded functionality is defined within the respective functions.

Kotlin program to demonstrate the unary operator overloading –

filter_none

edit
close

play_arrow

link
brightness_4
code

class UnaryOverload(var str:String) {
    // overloading the function
    operator fun unaryMinus() {
        str = str.reversed()
    }
}
// main function
fun main(args : Array<String>) {
    val obj = UnaryOverload("HELLO")
    println("Initial string is ${obj.str}")y
    //calling the overloaded function unaryMinus()
    -obj
    println("String after applying unary operator ${obj.str}")
}

chevron_right


Output:

Initial string is HELLO
String after applying unary operator OLLEH

Increment and Decrement Operators –

The increment and decrement operator can be defined for a type through the following functions. These function returns a new instance with the outcome of the expression.

Operator expression Corresponding function
++x x.inc()
– – x x.dec()

Either used in postfix or prefix notation these functions work well in both the cases, with the same expected output, as one would expect when using prefix or postfix notations.

Kotlin program to demonstrate the operator overloading –

filter_none

edit
close

play_arrow

link
brightness_4
code

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)
}

chevron_right


Output:

Hello
Helloa
Helloa
Hello

Binary Operators –

The following table shows the binary operators and their equivalent functions to be defined. All these functions modify the calling instance.

Operator expression Corresponding function
x1 + x2 x1.plus(x2)
x1 – x2 x1.minus(x2)
x1 * x2 x1.times(x2)
x1/ x2 x1.div(x2)
x1 % x2 x1.rem(x2)
x1..x2 x1.rangeTo(x2)

Kotlin program to overload the plus function –

filter_none

edit
close

play_arrow

link
brightness_4
code

class Object(var objName: String) {
    // Overloading the function
    operator fun plus(b: Int) {
        objName = "Name is $objName and data is $b"
    }
    override fun toString(): String {
        return objName
    }
}
// main function
fun main() {
    val obj = Object("Chair")
    // Calling the overloaded function
    obj+9
    println(obj)
}

chevron_right


Output:

Name is Chair and data is 9

Note- The relational operators do not have any specific functions to be defined, to use relational operators on instances of a user-defined type, the type must implement the Comparable interface.

Other operators –

Kotlin supports a wide range of operators, hence defining each for a type is not a good programming practice. The following table shows some of the other useful operators that can be overloaded is Kotlin.

Operator expression Corresponding function
x1 in x2 x2.contains(x1)
x1 !in x2 !x2.contains(x1)
x[i] x.get(i)
x[i, j] x.get(i, j)
x[i] = b x.set(i, b)
x[i, j] = b x.set(i, j, b)
x() x.invoke()
x(i) x.invoke(i)
x(i, j) x.invoke(i, j)
x1 += x2 x1.plusAssign(x2)
x1 -= x2 x1.minusAssign(x2)
x1 *= x2 x1.timesAssign(x2)
x1 /= x2 x1.divAssign(x2)
x1 %= x2 x1.remAssign(x2)


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.