Kotlin: Sealed Classes (enum 2.0)

Umang Kothari
AndroidPub
Published in
2 min readJan 5, 2020

This blog has also been published at author’s original website.

What is the sealed class?
Why do I need it?
How am I going to implement it?

We will see answer of all above questions.

Lets’ say, you want to create one class that has an only specific set of objects. E.g. Sunday, Monday, Tuesday etc. are only objects in a class named Day.

How are you going to implement this? I am pretty much sure that the first idea that has come to your mind is enum. And you are perfectly right. We can implement the above small class with enum like the following code- snippet:

enum class Days(dayNo: Int) {
SUNDAY(0),
MONDAY(1),
TUESDAY(2),
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6)
}

Now, you must be thinking then why do I need Sealed classes?

Before that, lets’ see what are the limitations of an enum:

  • We can create only a single instance for each enum constant. E.g. Sunday will always have the same state (dayNo: 0)
  • We can’t change the state for a given enum constant. E.g. In some country, week start from Monday so we need to set dayNo to 0 for Monday. But, enum can’t help
  • We can’t create a subclass of an enum constant

Sealed classes overcome the above limitations of enums. They are an extension of enums or enum 2.0.

Lets’ see a small example of implementation of Sealed class:

Here, Month is a sealed class and January, February, etc. are a subclass of Sealed class Month.

Some ground rules for sealed class:

  • We can create it by using sealed modifier before a class name
  • Its subclasses must be declared in the same file
  • It is by default abstract class
  • It has only private customer
  • Classes which extends subclasses of a sealed class can be placed anywhere, no need to put in the same file

Let’s see what are the advantages of using the sealed class:

  • We can create multiple instances for each subclass of the Sealed class because we can change the state of it.
    E.g. we can create two different objects of February (Feb 2019 and Feb 2020) and compare it
  • And also we can create a hierarchy of sealed class
  • If you are using “when expression” with sealed class then you don’t need to implement else case.

I guess that’s it in Sealed classes. Thank you very much for reading.

My objective is fulfilled if this would be the last blog for you to understand Sealed classes.

Let’s connect on Twitter and Medium. If you liked the article, click the heart below so more people can see it! Thanks for reading!

--

--