Predict the output
A teammate adds Empty to the sealed interface. What happens when you build?
sealed interface FeedState {
data object Loading : FeedState
data class Loaded(val items: List<String>) : FeedState
data class Failed(val message: String) : FeedState
data object Empty : FeedState
}
fun title(state: FeedState): String = when (state) {
FeedState.Loading -> "Loading"
is FeedState.Loaded -> "${state.items.size} items"
is FeedState.Failed -> state.message
}Hint 1 of 1
Does the when cover every subtype?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Compile error: the when must be exhaustive
Correct. The compiler knows every subtype and Empty isn't handled.
Why not the others?
- B It compiles and returns an empty string for Empty. There's no default; a when expression must cover all cases.
- C It compiles and throws at runtime for Empty. Kotlin catches this at compile time.
- D It compiles because data objects are ignored. Every subtype counts.