# Effective Kotlin Item 39: Use sealed classes and interfaces to express restricted hierarchies

This is a chapter from the book Effective Kotlin. You can find it on LeanPub or Amazon.

Sealed classes and interfaces represent restricted hierarchies, which means hierarchies with a concrete set of classes known in advance. Great examples are the BinaryTree (that is either Leaf or Node) and Either (that is either Left or Right). Such classes or interfaces have a concrete subset of children, that will never change.

sealed interface BinaryTree class Leaf(val value: Any?) : BinaryTree class Node(val left: Tree, val right: Tree) : BinaryTree sealed interface Either<out L, out R> class Left<L>(val value: L) : Either<L, Nothing> class Right<R>(val value: R) : Either<Nothing, R>

Sealed interfaces were introduced in Kotlin 1.5. Before that version, we had to use sealed classes, and its subclasses had to be defined in the same file.

Sealed classes are also used to represent hierarchies that might change in the future, but are considered final now. For instance, a set of operations we support, or messages an actor accepts.

sealed class ValueChange<out T> object Keep: ValueChange<Nothing>() object SetDefault: ValueChange<Nothing>() object SetEmpty: ValueChange<Nothing>() class Set<out T>(val value: T): ValueChange<T>() sealed class ManagerMessage class CodeProduced(val code: String): ManagerMessage() object ProductionStopped: ManagerMessage() sealed interface AdView object FacebookAd: AdView object GoogleAd: AdView class OwnAd(val text: String, val imgUrl: String): AdView

Notice, that when a class does not hold any data, we use an object declaration. It is an optimization to have one instance for all usages. Both creation and comparison are easier.

One might say that a sealed class or interface is a Kotlin way to express union types (also known as sum types or coproducts) — a set of alternatives. For instance, Either is either Left or Right, but never both.

Sealed classes are abstract classes, but because of their characteristics, they also have some additional restrictions on their subclasses:

• they need to be defined in the same package and module, where the sealed class is,
• they can't be local nor anonymous objects.

This means that when you use the sealed modifier, you control what subclasses a class or interface has. The clients of your library or module cannot add their own. No one can quietly add a local class or object expression extending this class. The hierarchy of subclasses is restricted.

### Sealed classes and when expressions

The usage of when as an expression, forces the user to return a value for every branch. In most cases, it cannot be guaranteed any other way but by adding an else clause. The power of having a finite type as an argument allows to have an exhaustive when with a branch for every possible value, which with sealed classes means is checks for all possible subtypes. Also, IntelliJ automatically suggests adding remaining branches. Those two make sealed classes very convenient to check for all possible types.

sealed class Response<out R> class Success<R>(val value: R): Response<R>() class Failure(val error: Throwable): Response<Nothing>() fun handle(response: Response<String>) { val text = when (response) { is Success -> "Success with \${response.value}" is Failure -> "Error" // else is not needed here } print(text) }

Notice that when the else clause is not used, and when we add another subclass of this sealed class, the usage needs to be adjusted by including this new type. This is convenient in a local code - forces us to handle the new class in most of the cases where we need to. The inconvenient part is, that when this sealed class is a part of the public API of some library or shared module, adding a subtype is a breaking change.

### Summary

Sealed classes and interfaces should be used to represent restricted hierarchies. They make it easier to handle each possible value, and as a result to add new methods using extension functions. Abstract classes leave space for new classes joining this hierarchy. If we want to control what the subclasses of a class are, we should use the sealed modifier. We use abstract mainly when we design for inheritance.