Kotlin-Sealed Class(with examples)

Zehra Yılmaz
Huawei Developers
2 min readMay 27, 2021

--

Hi folks. In this article, I will tell you about Kotlin sealed classes and show the differences and similarities between enums. Kotlin sealed keyword first appeared in Kotlin version 1.4.3 and developed through 1.5.

First, let’s start with the keyword, “sealed”; it means restricted and just like its meaning, helps us to make classes to have a restricted inheritance. To give it a detailed explanation, sealed classes cannot be inherited from other packages, it is only allowed in same module classes. This explains the sentence below:

All subclass of a sealed class are known at compile time.

So, every subclass of a sealed class is known when the class is compiled.

There is another advantage of sealed class besides restricted hierarchy, using when keyword as expression (shown in example below) does not need an else case, because every subclass of a sealed class is known, means all cases are covered while using an instance of a sealed class in when expression. Let’s see the example :

Suppose we have a sealed class named “Room” and three classes inherited this class (LivingRoom, Bathroom and Kitchen).

While we are trying to use when expression, we will have something like ;

And magic happens ! There is no error says

You need to add an else branch 

cause as we said before, all subclass of a sealed class are known and there is no other case.

Seems familiar ?

Enum vs Sealed

We know enums are basic constant data sets and also have restricted set of values, just like sealed classes.

However, there is a certain difference between these two. Enums are managed through a single instance. What do I mean by that? Let’s give an example;

Suppose have an Enum class called RoomType;

When we try to create an array of rooms, we will do it like (refer to example above):

But if we create an array of room types, it will be like:

As you see, we create a new instance for each different room but when it came to the room type, we used a single instance and reach different types.

That’s it. Now, you learn the basics of sealed classes and the key difference between enum.

References

--

--