🐦 Kotlin Beginner

What is a sealed class in Kotlin?

Answer

A sealed class is an abstract class whose subclasses must all be defined in the same package and module (in Kotlin 1.5+, the same file was the original requirement). This gives the compiler complete knowledge of all possible subtypes. The key benefit is exhaustive when expressions — when you match over a sealed class, the compiler knows all subclasses and will warn (or error) if you forget to handle one, without needing an else branch. Sealed classes are the idiomatic way to model restricted hierarchies like network results, UI states, or navigation events.