Kotlin Sealed Classes

Working with states can be a hassle! I used enums to check which state the application was in. For instance when the application was in an error state I assigned the enum value to ERROR but there wasn’t a data holder where I could place my exception. Enum’s can hold data but for every instance it is the same. Therefor I always created some kind of Response object that holds the state with the exception and perhaps other values.

But as you can see, now I have nullable parameters which I need to check.. not that nice..

But then Kotlin came along with “Sealed classes”!

Sealed classes, are in a sense, an extension of enum classes. The set of values for an enum type is also restricted like a sealed class. The only difference is that, enum can have just a single instance, whereas a subclass of a sealed class can have multiple instances.

So instead of using an enum for my state, I can use subclasses of a sealed class the set my state which can hold my data aswell.

To demonstrate the restricting of creating subclasses I also made an example with an normal open class. But here, it’s mandatory to use else branch for default condition in when expression. Which isn’t nice at all.

Code can be found here

External links:

  • https://kotlinlang.org/docs/reference/sealed-classes.html
  • https://www.programiz.com/kotlin-programming/sealed-class
  • https://proandroiddev.com/kotlin-sealed-classes-enums-with-swag-d3c4b799bcd4
  • https://www.baeldung.com/kotlin-sealed-classes

 

One Comment

Leave a Reply to Site Cancel reply

Your email address will not be published. Required fields are marked *