Junior — Middle
What is the purpose of a class declared with the sealed modifier?
sobes.tech AI
Answer from AI
A class declared with the sealed modifier is intended to restrict inheritance. Such a class can have subclasses, but only those declared in the same file. This allows controlling and fixing the inheritance hierarchy, making it more predictable and safe.
For example, in Kotlin, sealed classes are often used to represent a limited set of states or options, which is convenient when working with when expressions, where the compiler can check for exhaustiveness.
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val error: Throwable) : Result()
}
fun handleResult(result: Result) {
when(result) {
is Result.Success -> println("Data: ${result.data}")
is Result.Error -> println("Error: ${result.error.message}")
}
}