Interview frequency: …
Short answer
An enum represents a fixed set of identical single values, while a sealed class represents a restricted hierarchy that lets each branch own its own state and data.
Explanation
A sealed class/interface is the ideal choice for representing UI states and events in an MVI/MVVM architecture, because each state (such as Loading, Success, or Error) may need completely different data. Both kinds allow an exhaustive when expression without needing an else branch.
Code example
sealed interface UiState {
data object Loading : UiState
data class Success(val data: List<String>) : UiState
data class Error(val exception: Throwable) : UiState
}
fun render(state: UiState) = when (state) {
is UiState.Loading -> showProgressBar()
is UiState.Success -> showList(state.data)
is UiState.Error -> showError(state.exception.message)
// No else is needed because all cases are fully covered
}Common mistakes
- Using an enum for states that need variable data such as an error message or a data list.
- Adding an unnecessary else branch in a when over sealed classes, which deprives the developer of the compiler's warning when a new state is added later.