Junior — Middle
Что подразумевается под классом с ограниченным наследованием и как он используется в Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a class with restricted inheritance is a class that cannot be inherited arbitrarily, but only from certain classes or in specific modules. This is achieved using the sealed keyword (sealed class).
Sealed classes allow you to restrict the inheritance hierarchy: all subclasses must be declared in the same file as the sealed class itself. This is convenient for implementing a limited set of options, for example, when working with states or results.
Example of using a sealed class:
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val error: Throwable) : Result()
object Loading : Result()
}
fun handleResult(result: Result) {
when(result) {
is Result.Success -> println("Data: ${result.data}")
is Result.Error -> println("Error: ${result.error.message}")
Result.Loading -> println("Loading...")
}
}
Thus, a sealed class restricts inheritance and allows the compiler to check the completeness of when expressions.