Operator overloading

Operator overloading is a mechanism where programming language operators are implemented in custom, user-defined types. Most of the operators in Kotlin are actually functions. If you define a function in your type named plus, then you can use the + operator with the instance of that type. This increases flexibility and allows you to have a type defined in Java, and then use operators instead of functions in Kotlin. Also, thanks to extension functions, this enables adding an operator to existing types that you don't own.

The following table shows how operators map to functions:

Operator

Function

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.rem(b)

a..b

a.rangeTo(b)

a in b

b.contains(a)

a[i]

a.get(i)

a[i] = b

a.set(i, b)

a += b

a.plusAssign(b)

a -= b

a.minusAssign(b)

a *= b

a.timesAssign(b)

a /= b

a.divAssign(b)

a %= b

a.remAssign(b)

a == b

a.equals(b)

a > b

a.compareTo(b) > 0

a < b

a.compareTo(b) < 0

a >= b

a.compareTo(b) >= 0

a <= b

a.compareTo(b) <= 0

Operator overloading can make the code easier to understand. Let's say that you have two instances of Java's BigInteger class. They represent numbers and it would make the code easier to understand if we used the + operator to sum them, instead of calling the add function.

Let's say we've defined a type that represents a length of something. To keep it simple, we have only one property that represents the value of the length. It seems natural to use the + operator to add two lengths, so we're going to overload that operator. We have to find the function name of that operator and implement it with the operator keyword:

class Length(val value: Double) {
operator fun plus(other: Length): Length {
return Length(this.value + other.value)
}
}

Now, we can add two lengths with the + operator:

val l1 = Length(12.0)
val l2 = Length(23.5)

val sum = l1 + l2

Have you noticed how the plus function accepts an instance of another Length class? If we wanted to use the + operator with other types, we'd just have to implement another plus function that accepts that type. Let's now make it possible to call the + operator with doubles:

operator fun plus(double: Double): Length {
return Length(this.value + double)
}

And now, we can use doubles with the + operator:

val l3 = Length(10.0)
val sum1 = l3 + 12.0

The return type of an operator function doesn't have to return the same type as the containing class. Here's how we can overload length and string to return another string:

operator fun plus(str: String): String {
return "$value $str"
}

If we now pass a string to the + operator, we'll get a string as return type:

val str: String = l1 + "kilometers"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.186.143