Sealed Classes and Exhaustive when

Article · 2:00

Making invalid states unrepresentable, and letting the compiler find every place that must change.

A sealed class or interface restricts its subclasses to a set the compiler knows completely at compile time. That single fact has a large consequence: a when over a sealed type does not need an else branch, because the compiler can verify every case is covered - and will refuse to compile if one is missing.

This turns a common runtime bug into a compile error. Add a fourth state to a sealed hierarchy and every exhaustive when across the whole codebase stops compiling until you handle it. Compare that with an enum plus a default branch, where the new case silently falls into the default and ships.

The canonical use is modelling the outcome of an operation that can succeed, fail, or be in progress. Instead of a class with a nullable data field, a nullable error field and a boolean loading flag - eight combinations, of which three are valid - a sealed hierarchy makes the invalid combinations impossible to construct.

Use data object for states carrying no data, so you get a sensible toString and a single shared instance. Sealed interfaces, unlike sealed classes, allow a type to participate in more than one hierarchy, which is occasionally exactly what a domain needs.

sealed interface LoadState {
    data object Loading : LoadState
    data class Success(val items: List<String>) : LoadState
    data class Failure(val reason: String) : LoadState
}

// No else branch: the compiler proves every case is handled
fun render(state: LoadState): String = when (state) {
    is LoadState.Loading -> "Spinner"
    is LoadState.Success -> "${state.items.size} items"   // smart cast
    is LoadState.Failure -> "Error: ${state.reason}"
}

fun main() {
    val states = listOf(
        LoadState.Loading,
        LoadState.Success(listOf("a", "b", "c")),
        LoadState.Failure("no network"),
    )
    states.forEach { println(render(it)) }
}

Discussion

No questions on this topic yet. Sign in to ask the first one.