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
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