Sealed classes restrict inheritance to a known set of subclasses in the same module—ideal for modeling closed hierarchies like UI states or network results, similar in spirit to C# discriminated unions with when exhaustiveness.
Sealed hierarchy
sealed class Result {
data class Ok(val value: String) : Result()
data class Err(val message: String) : Result()
}
fun describe(r: Result) = when (r) {
is Result.Ok -> "OK: ${r.value}"
is Result.Err -> "ERR: ${r.message}"
}
Subclasses must be direct—nested classes, objects, or data classes in the same file or module per visibility rules.
Important interview questions and answers
- Q: Sealed vs enum?
A: Enums are fixed constant sets with one instance each; sealed classes carry distinct data per subtype. - Q: Why sealed with when?
A: Compiler can verify exhaustivewhenbranches when all subclasses are known.
Self-check
- What control flow pairs well with sealed types?
- Can sealed subclasses live anywhere in the project?
Tip: Pair sealed hierarchies with exhaustive when—great for UI state and API result modeling.
Interview prep
- Why sealed?
Restrict subclasses for exhaustive when and API safety.
- sealed vs enum?
Sealed for rich per-case state; enum for fixed constants.