What if your program could warn you when you forget to handle a case? Sealed classes make that happen!
Why Sealed classes for restricted hierarchies in Kotlin? - Purpose & Use Cases
Imagine you have a set of related types, like different shapes: Circle, Square, and Triangle. You want to handle each shape differently in your code. Without a clear way to restrict which shapes exist, you might accidentally add unsupported shapes or forget to handle some cases.
Manually managing all possible types is slow and error-prone. You might miss a shape when writing code, causing bugs. Also, adding new shapes anywhere in the code can break existing logic without warning. This makes your program fragile and hard to maintain.
Sealed classes let you define a fixed set of subclasses in one place. This means the compiler knows all possible types and can help you check that you handle every case. It prevents unexpected types from sneaking in, making your code safer and easier to understand.
open class Shape class Circle : Shape() class Square : Shape() // Someone adds Hexagon later fun draw(shape: Shape) { if (shape is Circle) { /*...*/ } else if (shape is Square) { /*...*/ } // No check for Hexagon! }
sealed class Shape { class Circle : Shape() class Square : Shape() } fun draw(shape: Shape) = when(shape) { is Shape.Circle -> { /*...*/ } is Shape.Square -> { /*...*/ } // Compiler warns if a case is missing }
It enables safer and clearer code by restricting and controlling all possible types in a hierarchy.
Think of a traffic light system with fixed states: Red, Yellow, Green. Using sealed classes ensures you only have these states and handle each one properly, avoiding unexpected errors.
Sealed classes restrict which subclasses can exist.
This helps the compiler check all cases are handled.
It makes your code safer, clearer, and easier to maintain.