Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 134 ยท Classes and Objects

Sealed Classes and Interfaces

Learn Kotlin sealed classes and sealed interfaces: closed hierarchies, exhaustive when without else, modeling results and UI states, rules for subclasses, and sealed vs enum.

An enum is a fixed list of constants. But real problems often have a fixed list of shapes, where each shape carries different data. A network request is loading (no data), succeeded (with a body) or failed (with an error). A payment is cash, a card (with a number) or a transfer (with an account). You want the compiler to know that these are the only cases, so that a when over them can be checked for completeness.

That is the job of sealed classes and sealed interfaces. A sealed type has a closed, known set of direct subtypes. Anyone can use it, but nobody outside its package and module can add a new subtype. This lesson shows how to declare one, how when becomes exhaustive without else, how to model results and states, and where sealed types differ from abstract classes and enums.

A first sealed hierarchy

Declare the parent with sealed and put its subtypes next to it:

Kotlin Shapes as a sealed hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at area(). The when has three branches and no else, yet it compiles, because the compiler knows Circle, Rectangle and Empty are all the subtypes of Shape. Inside each is branch, shape is smart-cast to the specific class, so shape.radius is allowed. The data object has a readable toString() (see Data Classes).

A sealed class is abstract by default and cannot be instantiated; Shape() alone is an error. Its constructors are protected (or private) by default.

The big payoff: exhaustiveness

The reason sealed types exist is what happens when the hierarchy grows. Add a Triangle and every when that forgot it stops compiling:

Kotlin Forgetting a subtype (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports error: 'when' expression must be exhaustive. Add the 'is Triangle' branch or an 'else' branch. Compare this with an open abstract hierarchy, where a forgotten case would only be discovered as a wrong result at run time. The same safety is why you should avoid else in a when over a sealed type: else would hide the very error the compiler wants to show you.

To get exhaustiveness checked on a when that is used as a statement, note that since Kotlin 1.7 statements over sealed, enum and Boolean subjects must be exhaustive too, so the check applies everywhere.

Sealed interfaces

A sealed interface is the same idea for interfaces. It matters because a class can implement many interfaces but extend only one class, so sealed interfaces let a type belong to several closed hierarchies at once:

Kotlin A sealed interface with shared and separate cases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Card and Transfer are both Payment and Refundable. The two when expressions are exhaustive over their own hierarchy. The subtypes here are top-level, which is allowed as long as they are in the same package and module as the sealed type.

Rules for subclasses

Direct subtypes of a sealed class or interface must be declared:

  • in the same package and the same module (compiled together) as the sealed type, but not necessarily the same file since Kotlin 1.5;
  • as ordinary classes, objects or data classes. They cannot be local or anonymous, and sealed interfaces cannot be fun interfaces.

Subtypes decide their own openness. A subclass can be final (the default), open, or itself sealed, which lets you build a tree:

Kotlin A sealed tree: JSON values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The nested when over JsonNumber is exhaustive because JsonNumber is itself sealed. This kind of tree, a small algebraic data type, is how parsers, expression evaluators and compilers are modeled in Kotlin. You will build one in Project: A JSON Parser.

Modeling results and states

Two uses cover most real-world sealed types. First, an operation that can succeed or fail without throwing:

Kotlin A sealed result type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The caller cannot forget the failure case, since the when will not compile without it. That is the idea behind Kotlin's own Result type, but a custom sealed type lets each failure carry exactly the data it needs.

Second, state: a screen or process that is in exactly one of several modes. Each mode carries only the data that exists in that mode, so impossible combinations (such as "loading with an error message") cannot be represented:

Kotlin State machine with sealed types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The function next is a pure transition: old state in, new state out. Because the states are immutable data, you can log every step, compare, and test them without any setup.

Sealed vs enum vs abstract class

Question enum sealed abstract / open
Fixed set of cases? Yes (instances) Yes (types) No
Different data per case? No (same properties) Yes Yes
Several instances per case? No (one each) Yes Yes
Exhaustive when? Yes Yes No
Extendable by other modules? No No Yes

Pick an enum when each case is a constant with the same fields. Pick a sealed type when cases have different data or can be created many times (every Card("...") is a new object). Pick an abstract class or open interface when other code, including other modules, must be able to add implementations, such as a plugin system.

A sealed class can also have a protected or private constructor with shared state, just like an abstract class. If every case shares the same fields, put them in the sealed parent and keep the subclasses small.

Pitfalls

  • Non-exhaustive else. Adding else -> to a when over a sealed type compiles but defeats the check. Use it only when "everything else" really is the right behavior.
  • Equality of objects. Cases without data should be data object (or object), so == and when branches such as Cash -> work and toString() is readable. Writing them as class Cash : Payment forces is Cash.
  • Binary and API compatibility. Adding a subtype to a sealed type that you publish in a library breaks users' exhaustive when expressions. That is a feature inside one codebase and a cost across library versions.
  • Too much nesting. Deep trees are hard to read. If you have more than two levels, check whether separate sealed types would be clearer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can a when over a sealed type omit else?

    A sealed type has a closed set of subtypes known at compile time, so the compiler can verify that every one is handled.
  2. 2. What is a key advantage of a sealed interface over a sealed class?

    Classes have single inheritance. Because a class can implement many interfaces, sealed interfaces allow a type to belong to multiple closed hierarchies.
  3. 3. Where must the direct subtypes of a sealed class be declared?

    Since Kotlin 1.5 they may live in different files, but they must be in the same package and module so the compiler can see them all.
  4. 4. When should you choose a sealed hierarchy instead of an enum?

    Enum constants are single instances that all share the same properties. Sealed subtypes can carry different data and be instantiated many times.
  5. 5. What happens to existing exhaustive when expressions when you add a new subclass to a sealed class?

    That is the point of sealing: the compiler lists every place that must handle the new case. A when with an else branch would not notice.

Summary

  • A sealed class or interface has a closed set of direct subtypes, declared in the same package and module.
  • A when over a sealed type needs no else, and the compiler reports every when that misses a case.
  • Sealed interfaces let one type belong to several closed hierarchies; subtypes can be classes, data classes, objects, or sealed themselves.
  • Use data object for cases without data and data classes for cases with data.
  • Sealed types model results and states without impossible combinations.
  • Pick enum for same-shaped constants, sealed for varied data, abstract or open for extension by others.

Next: Objects and Companion Objects