Kotlin Operator Overloading
In Kotlin, you can overload operators to give meaning to the standard operators like +
, -
, *
, /
, and so on, for your custom classes.
To overload an operator, you need to define a function with a special name that corresponds to the operator you want to overload. For example, to overload the +
operator for a custom class MyClass
, you need to define a function called plus()
:
class MyClass(val value: Int) { operator fun plus(other: MyClass): MyClass { return MyClass(value + other.value) } }
In this example, we define a custom class MyClass
with a single property value
. We then overload the +
operator by defining a function called plus()
that takes another MyClass
instance as a parameter and returns a new MyClass
instance with the sum of the two value
properties.
Once you have defined the plus()
operator function, you can use the +
operator on instances of your MyClass
class:
val a = MyClass(10) val b = MyClass(20) val c = a + b println(c.value) // prints 30
In addition to plus()
, you can overload other operators like minus()
, times()
, div()
, and many more. You can also overload comparison operators like ==
, >
, <
, and so on, by defining functions like equals()
, compareTo()
, and contains()
.
Operator overloading is a powerful feature that can make your code more expressive and intuitive. However, it should be used judiciously and only when it makes sense for your custom classes. Overloading operators can make your code harder to understand and maintain if overused or used inappropriately.