- Used to represent a restricted class hierarchy (useful for
when
expressions).
- All subclasses must be declared in the same file.
- Constructor is private by default
- Can have functions and abstract functions which the subclasses can implement
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
}
fun handleResult(result: Result) {
when (result) {
is Result.Success -> println("Success: ${result.data}")
is Result.Error -> println("Error: ${result.message}")
}
}