Junior — Middle
Mis on suletud klass ja millised on selle peamised eelised ja omadused?
sobes.tech AI
Vastus AI-lt
Sealed class is a special type of class in Kotlin (often used in Android development), which restricts the inheritance hierarchy. The main idea is that all subclasses of a sealed class must be declared in the same file as the sealed class itself.
Advantages and features:
- Allows the compiler to know the complete set of subclasses, which improves safety and convenience when working with
whenexpressions — the compiler will check that all cases are handled. - Simplifies modeling of limited hierarchies, such as states or events.
- Prevents creation of new subclasses outside the file, increasing control over architecture.
Example:
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}")
}
}