English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Sealed Classes (Sealed)

In this article, you will learn about sealed (sealed) classes with the help of examples, how to create them, and when to use them.

Sealed classes will be used when a value can only contain one type from a finite set (a restricted hierarchy).

Before we delve into sealed classes, let's discuss the problems they solve. Let's take an example:

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 (representing a number) and Sum (representing the sum of two expressions). Here, you must use an else branch to handle in the when expressiondefault condition.

Now, if you derive a new subclass from the Expr class, the compiler will not detect anything because the else branch will handle it, which may lead to errors. It's better if the compiler emits an error when adding a new subclass.

To solve this problem, you can use sealed classes. As mentioned before, sealed classes limit the possibility of creating subclasses. Moreover, when you handle all subclasses of a sealed class in a when expression, you do not need to use an else branch.

To create a sealed class, use the sealed modifier. For example,

sealed class Expr

Example: Example of sealed class usage

This is the method to solve the above problem using sealed classes:

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 the Expr class, unless the subclass is handled in the when expression, the compiler will report.

Several Important Points to Note

  • All subclasses of sealed classes must be declared in the same file as the sealed class they extend.

  • The sealed class itself isAbstractYou cannot instantiate objects from it.

  • You cannot create non-private constructors for sealed classes; by default, their constructors are private.

The Difference Between Enums and Sealed Classes

Enum ClassesSimilar to sealed classes. The set of values in an enum type is also restricted like sealed classes.

The only difference is that enums can have only one instance, while the subclasses of sealed classes can have multiple instances.