Problem Statement
How do sealed classes work with when expressions and why are they useful for representing state?
Explanation
Sealed classes restrict inheritance to a known set of subclasses defined in the same file, enabling exhaustive when expressions where the compiler verifies you've handled all possible cases without needing an else branch. When you use a sealed class in when, the compiler knows all possible subclasses and can check exhaustiveness at compile time, catching missing cases and providing better type safety than open hierarchies or enums.
Sealed classes are perfect for representing finite state machines, result types like Success or Error, or UI states in Android where you want type-safe state handling. Unlike enums which can only have single instances and limited data, sealed class subclasses can have different properties, multiple instances, and can be data classes or objects as needed.
Use sealed classes for discriminated unions, API response modeling where you have success with data and error with message, navigation destinations in Android, or any scenario with a closed set of possibilities. The combination of sealed classes and when expressions provides pattern matching-like capabilities with compile-time safety ensuring all cases are handled.
