Kotlin Sealed Class

Kotlin Sealed Class represent restricted class hierarchies, where a value can have a type from a restricted set.

Sealed Class Example

Following is an example of sealed class and sub-classes that extent sealed class.

A value of type ArithmeticOperation is restricted to Add, Subtract, Multiply and Divide.

This situation may look similar to that of Kotlin Enum. But the difference between Enum and Sealed Classes is that, in Enum there is only one value for each class type, whereas in Sealed Class, there could be multiple object instances for a class type (whose parent is a sealed class).

About Sealed Classes

  • A Sealed Class have specific number of sub-classes.
  • Location
    • All the classes that directly inherit a sealed class should be present in the same Kotlin file.
  • Constructors
    • Sealed Class cannot have non-private constructors.
    • Private is the default access modifier for constructors in Sealed Class.
  • Abstract
    • By default, a Sealed Class is abstract.
    • Hence, a Sealed Class cannot be instantiated and all other properties pertaining to Abstract Class hold for a Sealed Class.

Example – Kotlin Sealed Class with when expression

In the following example, a Sealed class with four sub-classes is considered and when expression is used for demonstrating the usage of Sealed Class.

This example could be considered a special case, where Kotlin When is used as an expression. In the execute() function, Kotlin Compiler makes sure that all the classes from the allowed sub-class set are addressed.