Simpler multiple click listeners with Kotlin Sealed classes

Paul Núñez
3 min readJul 3, 2017

--

With Kotlin came a lot of new concepts for the Android programming world and with them new possibilities for doing the same things on an easier way. One of those new concepts are Sealed classes that are, as said by Antonio Leiva in his post, enums with super-powers.

Enums with super-powers?

As you may know, enums can only have one object per type, while in the Sealed classes we can have several objects of the same class. What does this mean? let’s see the difference in the next example:

Difference declaring Enums and Sealed classes.

As you can see, Sealed classes help us set different behavior for each subclass as we can pass in the parameters we need.

But how can this be better for handling multiple click listeners?

Imagine you have a RecyclerView Viewholder, that has many views on a layout that can be clicked, something like this:

Update layout used in the following examples.

You could opt to create a normal interface with a method for each single view:

Updates layout listeners implemented with an interface.

Pass an instance to your adapter and then implement all the methods on your View. And this is totally fine! But each time you need to add a new method or change a method signature on the interface you’ll have to implement or change the signature on your View. And this is not ideal:

View implementing the Update layout listeners from the interface.

Another way is that if your click interactions are simple, you could use enums, but this is not a good idea, as said in a performance pattern video, we should avoid Enums.

So what do we have left? Sealed classes to the rescue!

The same interface can be changed to the following class, and create a simpler interface to handle all the listeners:

Sealed class implementation for the Updates Layout.

But now in your View, the implementation goes a lot simpler:

Sealed class listener implemented in only one method on the View.

Now you can add new methods, change the signature without too much effort and have all the code for the listeners encapsulated in one place, which is great!

Hope you enjoyed this post, you can follow me on twitter @paulnunezm where I usually tweet about Android Dev. And let please let me know what you think in the comment section bellow.

--

--

Paul Núñez

Trying to ship better code a Bit at a time @Pinger. Mostly write about Android development. Dominican 🇩🇴🌴.