Sealed Classes
Explore the concept of sealed classes in Kotlin and how they serve as a controlled base for specific subclasses within the same file. Understand their instantiation rules and how they enhance safety by ensuring exhaustive handling in when expressions. This lesson helps learners manage class hierarchies and inheritance with precision.
We'll cover the following...
In Kotlin, on one extreme we have final classes—that is, classes not marked as open—which can’t have any derived classes. On the other extreme we have open and abstract classes, and there’s no telling which class may inherit from them. It’ll be nice to have a middle ground for a class to serve as a base to only a few classes, which the author of the class specifies.
How sealed classes work in Kotlin
Kotlin’s sealed classes are open for extension by other classes defined in the same file but closed—that is, final ...