Junior — Middle
What is a sealed class and what are its main advantages and features?
sobes.tech AI
Answer from AI
Sealed class — a special type of class in Kotlin (often used in Android development) that 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 restricted hierarchies, such as states or events.
- Prevents creation of new subclasses outside the file, enhancing 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}")
}
}