Kotlin Sealed Classes

Sealed classes are used when a value can have only one of the types from a limited set (restricted hierarchies).


Before going into details about sealed classes, let's explore what problem they solve. Let's take an example (taken from official Kotlin website - Sealed classes article):

class Expr
class Const(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr

fun eval(e: Expr): Int =
        when (e) {
            is Const -> e.value
            is Sum -> eval(e.right) + eval(e.left)
            else ->
                throw IllegalArgumentException("Unknown expression")
        }

In the above program, the base class Expr has two derived classes Const (represents a number) and Sum (represents sum of two expressions). Here, it's mandatory to use else branch for default condition in when expression.

Now, if you derive a new subclass from Expr class, the compiler won't detect anything as else branch handles it which can lead to bugs. It would have been better if the compiler issued an error when we added a new subclass.

To solve this problem, you can use sealed class. As mentioned, sealed class restricts the possibility of creating subclasses. And, when you handle all subclasses of a sealed class in an when expression, it's not necessary to use else branch.


To create a sealed class, sealed modifier is used. For example,

sealed class Expr

Example: Sealed Class

Here's how you can solve the above problem using sealed class:

sealed class Expr
class Const(val value: Int) : Expr()
class Sum(val left: Expr, val right: Expr) : Expr()
object NotANumber : Expr()


fun eval(e: Expr): Int =
        when (e) {
            is Const -> e.value
            is Sum -> eval(e.right) + eval(e.left)
            NotANumber -> java.lang.Double.NaN
        }

As you can see, there is no else branch. If you derive a new subclass from Expr class, the compiler will complain unless the subclass is handled in the when expression.


Few Important Notes

  • All subclasses of a sealed class must be declared in the same file where sealed class is declared.
  • A sealed class is abstract by itself, and you cannot instantiate objects from it.
  • You cannot create non-private constructors of a sealed class; their constructors are private by default.

Difference Between Enum and Sealed Class

Enum class and sealed class are pretty similar. The set of values for an enum type is also restricted like a sealed class.

The only difference is that, enum can have just a single instance, whereas a subclass of a sealed class can have multiple instances.

Did you find this article helpful?