Kotlin - Sealed Class

In this chapter we speak Sealed Class of Kotlin programming language.

A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotlin file along with the sealed class. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed”

Let's see example

sealed class MyExample {
   class OP1 : MyExample() // MyExmaple class can be of two types only
   class OP2 : MyExample()
fun main(args: Array<String>) {
   val obj: MyExample = MyExample.OP2() 
   val output = when (obj) { // defining the object of the class depending on the inuputs 
      is MyExample.OP1 -> "Option One has been chosen"
      is MyExample.OP2 -> "option Two has been chosen"
In the above example, we have one sealed class named "MyExample", which can be of two types only - one is "OP1" and another one is "OP2". Now, as this “MyExample” class is sealed, we can apply the "when " clause at runtime to implement the final output.