IntermediateOOP
Sealed Class
Model limited states with sealed classes.
kotlin
sealed class Result
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
fun describe(result: Result): String = when (result) {
is Success -> "Got: ${result.data}"
is Error -> "Error: ${result.message}"
}
fun main() {
println(describe(Success("Loaded")))
println(describe(Error("Not found")))
}Output
Got: Loaded
Error: Not found
Explanation
sealed classes restrict subclassing to the same file. when is exhaustive — no else needed when all subclasses are covered.