👨💻Understand Kotlin Sealed class better!
Hi! Many Kotlin developers do not fully understand Sealed classes, and they are often confused with enum classes because of their similarity.
Sealed classes have always been a difficult topic for beginner developers to understand. Are you ready to end this here today? 👩🎓
Introduction
Hello Dear Kotlin lovers! Welcome to my new article. Today I’m going to explain Sealed classes. Before we get started, I recommend reading the article I wrote about Enum classes to get a better understanding of the subject!
First of all, I’d like to start by defining the Sealed class and talk about why we use it.
Sealed Class:
Sealed classes allow us to create classes that can be grouped in a limited set. As we will remember, Enum classes group finite datasets while Sealed classes allow us to write classes that can be grouped in finite set. Let’s understand this better with an example.
-Also, objects of Sealed classes cannot be created. Also, Constructors are always private.
-Likewise, Sealed classes are abstract classes. Since they are abstract classes, they cannot take the open and final keywords.(Unlike enums, these classes are not kept static in the background.)
-Furthermore, Subclasses that inherit sealed classes cannot be inherited because they are final. This feature is important for SDKs.
-In addition, object definitions can be made in Sealed Classes. However, if you only define an object in Sealed classes, it is technically no different than using an Enum. (Because all objects are kept statically in the background.)
-Moreover, since Sealed constants are all a class, we were able to implement interfaces to any constant that we wanted. We can’t do this with enum constants because we can’t add individual interfaces to our Enum constants, but our sealed constants are a separate class so they can be customized internally. (Enum constants do not behave like classes by nature.)
Conclusion
Sealed classes allow for grouping classes into a limited set, similar to enum classes. They are abstract classes with private constructors and cannot be instantiated. Subclasses that inherit sealed classes are final and cannot be inherited. Object definitions can be made in sealed classes, but they are no different from enum objects if only one object is defined. Sealed constants are a separate class and can implement interfaces, making them more customizable than enum constants.