Overview - Sealed classes
What is it?
Sealed classes in Kotlin are special classes that restrict which other classes can inherit from them. They let you define a fixed set of subclasses in one place. This helps the compiler know all possible types when you use them, making your code safer and easier to manage. Think of them as a closed family tree where only certain members are allowed.
Why it matters
Without sealed classes, developers often rely on open inheritance or enums that can't hold complex data. This can lead to bugs because the compiler can't check if all cases are handled, especially in when expressions. Sealed classes solve this by making the set of subclasses known and fixed, so the compiler can warn you if you miss a case. This reduces runtime errors and improves code clarity.
Where it fits
Before learning sealed classes, you should understand basic Kotlin classes, inheritance, and when expressions. After sealed classes, you can explore advanced Kotlin features like data classes, inline classes, and sealed interfaces. Sealed classes are often used in Android app state management and navigation logic.