Kotlin operator

Discover How To Overload Operators in Kotlin

In this article we will look at how to overload operators in Kotlin. Kotlin provides a way to overload operators in a very simple manner by making use of extensions and the “operator” keyword.

This makes the language very flexible and powerful! Let’s see how can we use it.

The operator keyword

We’ve seen how to use Kotlin extensions in our article “How To Use Kotlin Extensions“, this is precisely quite similar to the way Kotlin provides to allow overloading operators. The only difference in this case is that we’ll also have to use the operator keyword in our extension function to let Kotlin know that we also want to map that function to an operator.

For example, the “+” operator gets overloaded for collections in Kotlin by the following function.

public operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
if (elements is Collection) {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
} else {
val result = ArrayList<T>(this)
result.addAll(elements)
return result
}
}

For instance, in this case plus function is somehow associated with or translated to the “+” operator internally in the Kotlin compiler.

To check what operators are available, and therefore candidates for operator overloading, you can check the existing operators in Kotlin here.

In order to be able to overload the operators, you will need to know the “translation” of this operator to be able to tell Kotlin compiler what operator do we want to overload.

Although you could guess many of them, you can also find the “translations” for the following operations in the following links:

Having the mappings between operators and its corresponding translation or function name expected by the compiler, overloading an operator becomes very easy if you know how to use Kotlin extensions.

overload operator - kotlin
Photo by Ben Wicks on Unsplash

As always, it’s always easier to understand things when looking at an example. Let’s do it!

Overloading operator by example

Now that we have the basics of how operator overloading works, we can look at a simple example where we can understand the potential behind this feature.

Let’s assume we have a Coordinates class including latitude and longitude.

data class Coordinates(val latitude: BigDecimal, val longitude: BigDecimal)

As this is a new class we have created, if we try to add two coordinates using “+” operator the compiler will inform us that there’s a compilation error as it has no way to translate that to JVM bytecode.

How can we achieve that then? Let’s overload the plus operator to be able to add two coordinates.

operator fun Coordinates.plus(c2: Coordinates): Coordinates {
    return Coordinates(this.latitude + c2.latitude, this.longitude + c2.longitude)
}

As you can see, overloading “+” operator is quite easy! If we try to add two coordinates in a test now, let’s see what happens.

    @Test
    fun `should be able to use + operator to add coordinates`() {

        val c1 = Coordinates((-1.50).toBigDecimal(), 0.12.toBigDecimal())
        val c2 = Coordinates(1.32.toBigDecimal(), 0.122.toBigDecimal())

        val result = c1 + c2

        assertThat(result).isEqualTo(Coordinates((-0.18).toBigDecimal(), 0.242.toBigDecimal()))
    }

We can now use the “+” operator to add two coordinates in our test! We hope you found this straightforward and easy to understand.

If you are interested in knowing about Kotlin in more detail, we recommend the following books for your own reading:

Conclusion

We’ve seen how we can overload operators in Kotlin to be able to operate on some classes in a more expressive way. There are cases where this can be very useful and make our code more readable.

We have arrived to the end of our journey together today through this article. We really hope you liked this article and hopefully learned something new.

Follow us to get notified when new content gets published! Thanks and see you again very soon!