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:
1 |
sealed class ProductType() |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
sealed class ProductType() { class SimpleProduct(product: String): ProductType() class BundleProduct(product: String): ProductType() class ConfigurableProduct(product: String): ProductType() class DownloadableProduct(product: String): ProductType() } fun getProductType(typeId: ProductType) { when(typeId) { is ProductType.BundleProduct -> print("$typeId is bundle product") is ProductType.ConfigurableProduct -> print("$typeId is configurable product") is ProductType.DownloadableProduct -> print("$typeId is downloadable product") else -> print("$typeId is downloadable product") } } fun main(args: Array<String>) { getProductType(ProductType.SimpleProduct("testProduct")) getProductType(ProductType.BundleProduct("testProduct")) getProductType(ProductType.ConfigurableProduct("testProduct")) getProductType(ProductType.DownloadableProduct("testProduct")) } |
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.