Kotlin basics: sealed classes

“Beer bottle and their caps on a wooden drawer in the kitchen” by Adam Wilson on Unsplash

Sealed classes restrict the possibility of creating subclasses. It will help you to have control of how many subclasses have a class.

The when control expression in Kotlin is very powerful. It let us apply different actions depending on the type of a class.

But if using when you have to always add a default case using an else branch. This is not always “ideal”. Like in this case it is not possible to calculate the area of a polygon that we don’t know. Another potential error will show up if we add another subclass to Polygon and we forget to add it in the when construct of the area function.

To solve this issues we can add the modifier sealed to the polygon class. With that, we are telling kotlin that no other subclasses will subclass the Polygon interface.

Kotlin will:

  • Not allow to create a subclass of the sealed class unless its in the same file of the sealed class. (Note that a subclass of a sealed class subclass can be place out of the file where the sealed class is declared)
  • Make the sealed class open and abstract. It can not be instantiated directly.
  • Tell us to add all subclasses to the when expression or use an else branch. Never use an else branch on a sealed class or you will lose the benefits of it.

In the code above we can see different ways to implement a sealed class and its subclasses.

  • Triangle and Rectangle are nested classes of Polygon
  • Pentagon is a subclass data class of Polygon.
  • Hexagon is a subclass of Polygon declared in the same file and not nested.
  • Triangle is marked as open so it can be inherited by TriangleRectangle.
  • TriangleRectangle is a subclass of a subclass Triangle of the sealed class Polygon. It could be declared in a different file. In order for the when to use the TriangleRectangle branch it has to be positioned before its parent class Triangle. In other case it would always go thought the parent branch. Other important note is that Kotlin will not force to add the TriangleRectangle branch to the when.

Conclusion

Using sealed classes we can guarantee that the use of our class won’t be corrupted by a bad use of subclassing. Whenever you need to control how a class is subclassed use sealed classes instead of normal ones, and you will got a lot of benefits without effort.

Android-Kotlin Developer

Android-Kotlin Developer