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.
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:
- cannot be instantiated directly because they are
abstract(and therefore, they can have both abstract and non abstract methods and fields)
- can have subclasses and these can have multiples instances² which can contain their own state
- the type of such associated data may be different (see the example below)
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.
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.
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 🏆).
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.
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