Sealed Hierarchies: Introduction
An introduction to sealed classes and sealed interfaces, also called sum or union types, and a teaser for what they’re actually good for.
— — — — — — — — — — — — — — —
THE CURRENT VERSION OF THIS ARTICLE IS PUBLISHED HERE.
— — — — — — — — — — — — — — —

Tags: #KOTLIN FEATURE
This article is part of the Kotlin Primer, an opinionated guide to the Kotlin language, which is indented to help facilitate Kotlin adoption inside Java-centric organizations. It was originally written as an organizational learning resource for Etnetera a.s. and I would like to express my sincere gratitude for their support.
It is recommended to read the Introduction before moving on. Check out the Table of Contents for all articles.
Before we start, let me say that I honestly believe that the concepts discussed in the following chapters are among the most important things you can take away from the Primer — concepts which will open up your mind to new ways of designing, even outside of Kotlin, and make you a better programmer, period.
In this chapter, we will briefly discuss the concept of a sealed hierarchy, while the next chapters will delve into the techniques I just teased. Let’s go.
A sealed class (or sealed interface) represents a hierarchy which is determined at compile time. No other subclasses may appear after the module with the sealed hierarchy is compiled. For example, if your code is distributed as a library, users can’t extend your sealed hierarchy in their own code. Thus, each instance of a sealed class has a type from a limited set that is known when this class is compiled. Such a hierarchy is often called a union or sum type — a type that is a union (or sum) of a finite number of possibilities.
A sealed class or interface is declared with sealed class or sealed interface.
In some sense, sealed hierarchies are similar to enum classes: the set of values for an enum type is also restricted, but each enum constant exists only as a single instance, whereas a member of a sealed hierarchy can have multiple instances. It could be said that sealed hierarchies are the equivalent of enums in the type domain. If you created a sealed hierarchy consisting entirely of objects (i.e. singletons), you would have effectively created an enum.







