TIL about Operator Overloading in Kotlin and the Invoke Operator


Kotlin lets us define custom behaviour for operators (e.g. +, ==or *). We can add mathematical or logical semantics for how operators behave with various types.

We can either implement these behaviours in a class as a member function (handy for classes that we own), or externally, as an extension function (for types outside of our control).

First, let’s see what overloading is.

What is overloading?

Overloading functions is a practice which allow us to provide multiple functions with the same name (in the same scope), but with different signatures. This is desirable when the behaviour is the same or similar but the implementation has to be different for different types.

Consider the following class, which has a single function that’s used to sum two Int values together:

https://gist.github.com/ataulm/b3410adc85e0334fc40ff2ca679242e9

We can add a second function with the same name, in the same scope (in this class), but only if we change the parameters to alter the signature:

https://gist.github.com/ataulm/36de07490eadb61139d77dc2a5338c66

Now we can say that we’ve overloaded the “sum” function; whenever we call sum the function that it calls will depend on the types of the parameters we pass.

What is operator overloading in Kotlin?

Operator overloading is similar. Operators like minus, plus or equals have been defined to work with a subset of predefined types.

Let’s consider the minus function which works with some types, like Int:

minus(a: Int, b: Int)

or

a - b

where a and b are of type Int.

We learned at the start that we can overload operators by including them inside classes as member functions or outside classes as extension functions.

The minus operator has multiple overloads defined as member functions in the Int class:

https://gist.github.com/ataulm/10ec024227408c0e359268f5c98adaee

Let’s add another for a type that we define.

Overloading an operator for a new type

We have a data class that represents a tub (box?) of ice cream. It has one value, which is the number of scoops remaining in the tub (usually a low number for me):

https://gist.github.com/ataulm/569b85031bcf1e6061a393a17a44e94e

We want:

minus(a: IceCreamTub, b: Int)

We saw the overloading example with member functions above for Int, let’s demonstrate the same but using an extension function:

https://gist.github.com/ataulm/82ab3eaf283815486d7a5d128f5746ec

This will allow us to do something like this:

https://gist.github.com/ataulm/cd01715a0653691d9171bb0be4be57f2

Could we do the opposite?

https://gist.github.com/ataulm/1965aad215c43e688825001a877dcf57

It doesn’t compile because there’s no function minus defined on Int that has IceCreamTub as a parameter.

Let’s add it with an extension function (we can’t add a member function to the Int class directly):

https://gist.github.com/ataulm/d986e4c3b969d873164ca9013922e3f5

Oh. I actually don’t know what the return type should be for this function. It’s nonsense!

When should we (not) overload operators?

Problems, and critics, to the use of operator overloading arise because it allows programmers to give operators completely free functionality, without an imposition of coherency that permits to consistently satisfy user/reader expectations

from C++ Programming/Operators/Operator Overloading. No “imposition of coherency” mean that the writer is unrestricted to do what they like.

Did it make sense for us to overload the minus operator for IceCream ? The two units aren’t even comparable to each other so maybe it didn’t make sense in the first place.

https://gist.github.com/ataulm/552a7779e10b88e793f79ea5fe0a2a93

A regular function with a nicer name would serve us better.

We should be careful about overloading operators with types that might cause bewilderment (like with the Int and IceCreamTub combination) or worse, misunderstanding.

Useful instances of overloading

If you’ve used the Kotlin for even a few weeks, you’ll likely have come across instances of operator overloading already.

The Collection type overloads the plus operator. It lets us add elements from an Iterable<T> to a Collection<T>.

https://gist.github.com/ataulm/9f8f537c75043f3ee88d79b079c3db19

The plus operator is further overloaded to support appending single elements:

https://gist.github.com/ataulm/b71e68bf0a1f04bf27de0d4be2e8a70d

And it even works with collections of different types — in this case, the type of mix will be List<Any> :

https://gist.github.com/ataulm/8a31081d0e138a9ee61c06615860ae5c

Have a look at the full list of operators that can be overloaded on the Kotlin Language documentation site.

The invoke() operator

The invoke() operator allows instances of your classes to be called as functions.

Let’s create a class whose sole responsibility is taking a scoop of ice cream from the ice cream tub, then return the scoop and the tub (with the updated contents).

https://gist.github.com/ataulm/5686a3841da44cb0e054bfe0ce5b75ea

How would we use this?

https://gist.github.com/ataulm/68d6815644761da833200ecc8983a2f9

Our ScoopAction is only designed to do one thing — it’s a little clunky to have to call a function on a class that solely represents an action.

Instead, we could overload the invoke() operator:

https://gist.github.com/ataulm/d313500980de94e37e43ec179a59137e

The only differences are the addition of the operator keyword and usage of invoke as the function name.

https://gist.github.com/ataulm/0e36edfdef602f2001be22ef68a22c9b

We can further overload the same operator with more parameters:

https://gist.github.com/ataulm/9f448099bc9bbecb2cc8038d8b097cfa

Parentheses are translated to calls to invoke with appropriate arguments.

Have I been using the invoke() operator already?

The most common place we encounter the invoke() operator is with lambdas!

Lambdas are compiled to instances of the Function interfaces which all overload the invoke() operator:

https://gist.github.com/ataulm/e3a387cddf340fbdd71daea114774564

This lets us do the following:

https://gist.github.com/ataulm/b4fd35e13482d1e052bcdbf3fa9de25b

Instead of:

https://gist.github.com/ataulm/c267959761deec8251e572f483138c45

So… should I use this in my project?

We looked at what operator overloading is and how to do it in Kotlin. We see that the operators serve as a shorthand for function calls, and consequently anything written with an operator can be written explicitly with the corresponding function.

We write 1 + 2 instead of 1.plus(2) because it’s short, commonly understood and therefore easier to read, so we should apply the same logic when we’re deciding whether to overload operators with our own types:

  • is it clear what the behaviour should be?
  • would it be used often enough in your project to warrant the shorthand?

The invoke() operator is a little different. It still provides you with a shorthand, but has no inherent behaviour/meaning of its own — it lends your classes the property of being actionable. If your class:

  • represents a single action
  • is named for a specific action

then go for it!

It doesn’t require any extra lines of code, it supports and highlights the responsibility of a single action for your class and it reduces verbosity at the call site.

As always, questions and comments welcome either here or on Twitter!

Thanks Daniele, Nicole and Maria for reviewing, as well as Rebecca and Florina for discussing.

https://proandroiddev.com/til-that-you-can-use-the-invoke-operator-on-companion-objects-too-b0d21a870079