Kotlin
Sealed and state
Learn state management with sealed classes.
State management
Sealed classes are ideal for state management. A screen or operation can have mutually exclusive states like loading, success or error. Each state carries its own data.
Example: sealed class UiState; object Loading : UiState(); data class Success(val data: String) : UiState(); data class Error(val message: String) : UiState(). A UiState instance is in only one state at a time. when updates the UI per state; all states are checked, so no branch is forgotten. This simplifies complex state logic.
Loading, Success, Error
A UI state is usually in one of three states: Loading, Success (carries data) and Error (carries a message).
Example: object Loading : UiState(); data class Success(val data: String) : UiState(); data class Error(val message: String) : UiState(). Loading is a single state (object); Success and Error are data classes because they carry data. when produces a different UI per state: loading spinner, data list, error message. This pattern is common in Android and UI apps.
Exercise Render with the UiState sealed class
Define a sealed class named UiState. Add three subtypes: object Loading : UiState(), data class Success(val data: String) : UiState() and data class Error(val message: String) : UiState(). Write a function render(state: UiState): String whose body uses when (state) to return "loading" for Loading, state.data for Success and state.message for Error. In main create a Success("records") instance and print the result of render.
Show example solution
sealed class UiState
object Loading : UiState()
data class Success(val data: String) : UiState()
data class Error(val message: String) : UiState()
fun render(state: UiState): String {
return when (state) {
is Loading -> "loading"
is Success -> state.data
is Error -> state.message
}
}
fun main() {
val s: UiState = Success("records")
println(render(s))
}
Test yourself
-
Complete the sealed state definition
sealed ____ UiState
object Loading : UiState()
data class Success(val data: String) : UiState()
Show answer
sealed class UiState
object Loading : UiState()
data class Success(val data: String) : UiState()
-
Match the state pattern
- object Loading
- Singleton state
- data class Success
- State with data
- data class Error
- Error state
- when (state)
- Branch by state
-
Why use a sealed class for state management?
- Because a sealed class is fast at runtime
- Because all states fit in one variable
- Because a sealed class is a database
- Because the compiler checks all states and no branch is forgotten
Show answer
Because the compiler checks all states and no branch is forgotten — With a sealed class, when is exhaustive; no state branch is forgotten.
Next lesson: Sealed and result