DEV Community

loading...

Sealed (Class) with love

hector6872 profile image Hector de Isidro Updated on ・3 min read

Our new best travel companion ❤️

Among the many features that Kotlin brings to us to improve and facilitate our life while programming there are the Sealed Classes¹. These, combined with other features such as Smart Casting and When Expressions, will lead to a new and safer way to model our applications.

What is a Sealed Class?

Sealed classes are used for representing restricted class hierarchies…” - Mind blown / Mind explosion

Sealed Classes are said to be "Enum Types on steroids": they both are restricted hierarchies, they both represent a set, they both are types, and they both can contain associated data, but… the first ones:

Tip: if a subclass doesn’t keep state, it can just be an object.

Sealed Classes make our intentions clear (and their use also makes our code look cleaner)

Limitation (if we can call it that): subclasses must be declared in the same Kotlin file as the Sealed Class itself.

What about Smart Casting and When Expressions?

When Expression is the best partner for Sealed Classes. Using it as an expression makes it exhaustive: we will have to handle each and every one of its subclasses (or use an else clause in the worst case scenario 😞 ) or Kotlin’s compiler will complaint. This means that if we add a new subclass in the future, it will have to be handled as well.

Exhaustiveness Checking AKA let the compiler remind us we need to update our code

Going even further, thanks to the Kotlin’s Smart Casting feature, each subclass will be casted inside its is own clause, allowing us to access safely to its specific fields (saying goodbye to possible ClassCastException exceptions 🏆).

Tip: when comparing an object, as there’s only one instance, we don’t need to check its type, so we can avoid the use of the is operator

Using when as a statement doesn’t make it exhaustive. Fortunately, we can alter that behaviour by making use of another well-known Kotlin’s feature: extensions.

Ok, it seems quite cool but: can we test those Sealed Classes?

Of course, we can. In fact, we MUST do it 😉

Using Mockito as mocking framework for unit tests in Kotlin has some issues with the Kotlin’s Null-Safety feature because some of its matchers return Nulls, so we’ll have to use Mockito-Kotlin library which among other things solves these issues.

Last words

https://www.youtube.com/watch?v=apFIxtQdpek&t=33

The concept of the Sealed Classes is very simple but it’s the basis of a lot of new ideas and workflows. Please, feel free to let me know how you use them and why by leaving a comment below or tweet me over on @hector6872.

This article was originally published on Medium


[1] Yep, I’ve written a little about this before (look for “BONUS: Kotlin developers” part)
[2] Remember that a single-element Enum type is one of the best ways to implement a Singleton


External links 👀

Discussion (0)

pic
Editor guide