Kotlin – Sealed Class

Sealed class is a class which restricts the class hierarchy. A class can be declared as sealed class using “sealed” keyword before the class name. It is used to represent restricted class hierarchy.
Sealed class is used when the object have one of the types from limited set, but cannot have any other type.The constructors of sealed classes are private in default and cannot be allowed as non-private.  

  • Declaration of sealed class
sealed class MyClass

The subclasses of sealed classes must be declared in the same file in which sealed class itself.

sealed class Shape{
    class Circle(var radius: Float): Shape()
    class Square(var length: Int): Shape()
    class Rectangle(var length: Int, var breadth: Int): Shape()
    object NotAShape : Shape()
}

Sealed class ensures the important of type-safety by restricting the set of types at compile time only.

sealed class A{
    class B : A(){
        class E : A() //this works.
    }
    class C : A()init {
        println("sealed class A")
    }
}

class D : A() //this works{
class F: A() //This won't work,because sealed class is defined in another scope.
}

A sealed class is implicitly an abstract class which cannot be instantiated.

sealed class MyClass
fun main(args: Array<String>){
var myClass = MyClass() //compiler error. sealed types cannot be instantiated.
}
  • Sealed class with when

Sealed classes are commonly used with when expression. As the sub classes of sealed classes have their own types act as a case. Due to this, when expression in sealed class covers all the cases and avoid to add else clause.

sealed class Shape {
    class Circle(var radius: Float) : Shape()
    class Square(var length: Int) : Shape()
    class Rectangle(var length: Int, var breadth: Int) : Shape()
    // object NotAShape : Shape()
}

fun eval(e: Shape) =
        when (e) {
            is Shape.Circle -> println("Circle area is ${3.14 * e.radius * e.radius}")
            is Shape.Square -> println("Square area is ${e.length * e.length}")
            is Shape.Rectangle -> println("Rectagle area is ${e.length * e.breadth}")
            //else -> "else case is not require as all case is covered above"
            // Shape.NotAShape ->Double.NaN
        }

fun main(args: Array<String>) {

    var circle = Shape.Circle(5.0f)
    var square = Shape.Square(5)
    var rectangle = Shape.Rectangle(4, 5)

    eval(circle)
    eval(square)
    eval(rectangle)
}

Output :

Circle area is 78.5
Square area is 25
Rectagle area is 20

I hope you found what you were looking for from this tutorial. If you want more Kotlin tutorials like this, then do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂

Leave a Comment

Your email address will not be published.