In this tutorial you will learn about the Kotlin Sealed Class and its application with practical example.
Kotlin Sealed Class
The class which is declared with “sealed” modifier before the name of class known as sealed class. Sealed classes are used to represent restricted class hierarchies. A sealed class can have subclasses but all of them need to declare in the same file as the sealed class itself. In Kotlin sealed class we don’t need to use “else” statement.
Example: Let’s get understand it by an example, see below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
sealed class SealedDemo { class OPT1 : SealedDemo() // SealedDemo class can be of two types only class OPT2 : SealedDemo() } fun main(args: Array<String>) { val obj: SealedDemo = SealedDemo.OPT1() val output = when (obj) { // defining the object of the class depending on the inuputs is SealedDemo.OPT1 -> "W3Adda : Option One has been chosen" is SealedDemo.OPT2 -> "W3Adda : option Two has been chosen" } println(output) } |
Here, SealedDemo is a “sealed” class, which has two types: OPT1 & OPT2.
In the main class have created an object and assigned at run time.
Here we have applied “when” clause so that we can implement the final output at runtime.
Output: The output of this code will look like below image.