Tasty Kotlin Recipes #1: Operator Overloading

Who says +, -, and == are just for primitives? Welcome to the sweet world of Kotlin!

Introduction

Kotlin has a plethora of great syntastical sugars that make it such a joy to use. This article will cover a lesser used feature of Kotlin, operator overloading. Before we begin, it is worth knowing that operator overloading is a feature that is part of Kotlin conventions. Conventions can be seen as a technique that Kotlin enables by allowing the user to write their own implementation for various aspects of the language. These include, but are not limited to, delegate properties for setters and getters, overriding component functions for classes to return multiple values, and our topic: operator overloading.

All Java developers know that when you are looking at string equality, you can’t use the infix ‘==’, instead you have to use equals(). As well, when you override the equals method for your classes, you will obviously have to use equals() to compare equality… but what if you didn’t have to. Well, Kotlin once again comes to the rescue, when your Kotlin code gets compiled, == gets replaced with the method call to equals(). This means that you can use the shorter, and much more expressive ‘==’ to compare your strings and any objects you want. Well that is quite nice, but what if we could take this one step further, what about ‘+’, ‘<=’, and other operators? Well with Kotlin, you can provide your own implementation for all those operators to make your code much cleaner.

To show how you can get started overriding your own operators, I will show two example use cases where ‘+’ and the comparison operators (‘>=’, ‘<’, etc) will be overrode, then I will simply put a table of operators and their corresponding methods to override since the rest will become easy to figure out after the following example.

Operator Overloading Examples

Here’s our sample class:

Overriding ‘+’ and standard operators

First, we’ll take a look at the simpler operator we just overrode, ‘+’. Notice the ‘operator’ before ‘fun’, please don’t misread that as ‘override’ as I did the first time I used it. For the majority, although not all, of the operators you will need to use the operator keyword. Now onto the method itself, let's first look at how this method gets called under the hood. This:

a + b

Turns into this:

a.plus(b)

It’s just that simple. However, at this point you may be wondering if the parameter of the plus method needs to have a matching type to the surrounding class and the return type, well… not at all! The following implementation for the plus operator in the DanceGroup class would be perfectly valid:

operator fun plus(moreMembers: ArrayList<String>): Boolean {
return true;
}

While it doesn’t make sense to do that, it shows the flexibility that you have.

Comparable operators

Now we can explore the comparable operators, namely >=, >, <, and <=. All of these can be changed in one swoop by using a technique that Java developers should recognize: implementing the Comparable interface. You then override (Notice that we are not using the operator keyword now) the compareTo method and return -1 if the surrounding object is less than the parameter object, 0 if it is the same, and 1 if it is greater. Due to the fact that we are overriding the method, we don’t have the same flexibility with parameter type and return type. To make things easier, you can use the compareValuesBy method and pass it the two objects (in correct order) and how to compare them. To truly appreciate just how clean things have now become, let’s look at an example between Java and Kotlin where we will compare two variables of the same type, a and b, which both use the comparable interface.

In Java:

int result = a.compareTo(b);
switch (result) {
case -1: {
// b is greater than a
}
case 1: {
// a is greater than b
}
case 0: {
// a and b are equal
}
}

And now in Kotlin:

// Choose one of the following
a >= b
a > b
a <= b
a < b

Begone compareTo and large switch/ifelse statements, and hello those sweet operators. With those two use cases, the following table will be easy to understand and a great cheatsheet to override your own operators in the future.

Image for post

Conclusion

I rarely see Kotlin developers override operators, I don’t even do it that often, but when use appropriately it can make for some very nice code. Personally I find the most use for the new syntax with the comparable operators which would need large chunks of code (relatively) to use the compareTo method previously. For more information, check out Kotlin in Action and Kotlin website.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store