Kotlin Sealed Class

Kotlin provides sealed class to restrict inheritance hierarchy. This sealed class is not provided in the Java programming language. Kotlin has added this just for safety purpose.

A sealed class can have subclasses that need to be declared along with sealed class. A subclass of a sealed class can have multiple instances. Sealed class is abstract by itself, so we cannot instantiate it directly, but from subclasses. It can also have abstract members, which must be implemented by all subclasses of the sealed class. In sealed class, all constructors are private by default.

Creating a Sealed Class

sealed class className

To create a sealed class, sealed modifier is used before the class.

sealed class MetroCity{


Implementing Sealed Class

In the below example, we have created a sealed class MetroCity and two subclasses m1 and m2.

sealed class MetroCity{
	class m1 : MetroCity()
	class m2 : MetroCity()

Sealed Class Constructor

The sealed class constructor is private by default.

sealed class MetroCity(var name:String){
    class m1 : MetroCity("Delhi")
    class m2 : MetroCity("Pune")
fun main(args : Array<String>)  { 
    var x = MetroCity.m1().name
    var y = MetroCity.m2().name

In the above example, we have created a Sealed class 'MetroCity' and its two subclasses m1 and m2. In the main method, we have accessed the property's value by instantiating the subclasses.

Sealed class and when

It is beneficial to use sealed class with when expression, as each of the subclasses of sealed class act as a case. So the else part of the when statement can be easily removed.

sealed class Plant{
    class Leaf(var color: String) : Plant()
    class Flower(var color: String) : Plant()
fun evaluate(e: Plant) =
    when(e) {
        is Plant.Leaf -> println("Color of leaf is ${e.color}.")
        is Plant.Flower -> println("Color of flower is ${e.color}.")
fun main(args : Array<String>)  { 
    var leaf = Plant.Leaf("green")
    var flower = Plant.Flower("red")

Color of leaf is green.
Color of flower is red.

Read more articles

General Knowledge

Learn Popular Language