Sealed classes in Kotlin

Updated 30 September 2022

Save

In this blog, we going to discuss Sealed classes in Kotlin.

Before going to start the sealed classed we all know about the inheritance. Inheritance is the process of driving the new sub class from the parent class. Sub class extends the all functionality of the parent class and can be able to override parent class functionality with there own.

Sealed classes in Kotlin provides the restriction to the class hierarchies. We use sealed class to define a set of sub classes in it.

So the type of the sub classes are know in advance at the compile time it ensure the type safety in the sealed classes as well.

Sealed classes constructor are private by default and can’t be allowed as non private.

For creating the sealed class just add the sealed keyword before the class like below:

Sealed classes are abstract classes and we can not create the instance of the sealed classes.

Sealed classes have the sub classes inside the same file or nested inside the sealed class itself.

We have used the sealed class with the when keyword will help to check the type and prevent us from the if else leader.

Sealed classes sub classes can be created on the same file. Sub classes of the sealed classes sub class can be created on the same package.

So in the sealed classes we know the class hierarchy in advance so no one can access or inherits of class at further on runtime.

Conclusion:

In this blog, we have learned Sealed classes in Kotlin and how to create sealed classes and its uses.

For more information regarding the Sealed classes in Kotlin follow link.

Thanks for reading this blog. You can also check other blogs from here.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home