Sealed class — enum with special powers

Sealed Classes in Kotlin

Learn how to use sealed classes in Android

Introduction

Sealed Classes in Kotlin is another new concept which we don’t have in traditional Java. Sealed class is sort of an extension to the traditional ENUM classes.

A sealed class allows you to represent constrained hierarchies in which an object can only be of one of the given types.

That means, we have a class with a specific number of subclasses. What we have in the end is very similar to an enum. The difference is that in the enum we only have one object per class, while in the sealed classes we can have several objects of the same class. This difference will allow objects from a sealed class to keep state.

How to create sealed classes

To declare a sealed class, you put the sealed modifier before the name of the class. A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself. Have a look

Sealed class creation

Above code represents a sealed class which I used in one of my projects to maintain network communication through livedata between view-model to fragment.

Loading — To know Start and end of service calls to show and hide loading.

CustomSignal — This is used to send a simple signal like a message or code

CustomSignalDetailed — This is just like CustomSignal but we have more control and scope to include more data like custom classes as signals like ErrorCaseData I used in the above code.

Failure — This is used to communicate through throwable

How to use sealed classes

Now that we know how to create sealed class, it’s time to use it. As I mentioned I’ve used above sealed class to communicate from view-model to fragment.

To know in-detail of how to use sealed class we have to understand two things

  1. Where & how the data is updated.
  2. Where & How the Data is Used.

Where & how the data is updated

In my case I’ve to update the sealed class livedata in the viewmodel after or before service calls. Have a look

update sealed class data

Where & How the Data is Used

Now we need to see how to use the data posted in view-model have a look

use sealed class data

You can find me on Medium, Twitter and LinkedIn Cheers!

Thank you for reading.

Learn. Code. Write. Repeat. Visit me at https://about.me/sivaganesh_kantamani & Join my email list at https://sgkantamani.substack.com/p/subscribe

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store