Junior — Middle
Milliseid eeliseid ja kasutusstsenaariume sa tead sealed class Kotlinis?
sobes.tech AI
Vastus AI-lt
Sealed class in Kotlin is used to restrict the inheritance hierarchy. All subclasses of a sealed class must be declared in the same file as the sealed class itself. This allows the compiler to know all possible variants of subclasses, which is useful for use in when expressions without needing to write an else branch.
Advantages:
- Type safety: the compiler checks the completeness of handling all variants.
- Convenient for modeling limited sets of states or events.
Use cases:
- Implementation of states in the "state" pattern.
- Processing of events or commands.
- Representation of a limited set of options, e.g., API responses.
Example:
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...")
}
}