Junior — Middle+
Example of using a sealed class to describe different states
livecode
Task condition
Demonstrate how a sealed class can be used to model a set of possible states of an object. Show the declaration of a sealed class and several of its subclasses, each representing a separate state, as well as an example of usage in a when (or similar) conditional operator without the need to add an else branch, since the compiler will check for exhaustiveness.
sealed class UiState {
object Loading : UiState()
data class Success(val data: List<String>) : UiState()
data class Error(val cause: Throwable) : UiState()
}
fun render(state: UiState) {
when (state) {
is UiState.Loading -> println("Loading...")
is UiState.Success -> println("Data: ${state.data}")
is UiState.Error -> println("Error: ${state.cause.message}")
}
}
The example shows how a sealed class guarantees a complete set of options and simplifies working with different states in the code.