ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Kotlin Tutorial• 7 min read

When Expressions & Sealed Classes: Pattern Matching

Exhaustive pattern matching with when and restricted class hierarchies

The when expression replaces clunky switch statements with pattern matching, while sealed class defines closed type hierarchies verified by the compiler.

Sealed Class State Modeling

sealed class: Represents restricted class hierarchies where all subclasses are known at compile time. Ideal for UI State (Loading, Success, Error).

Exhaustive when: When using when on a sealed class, the compiler ensures every possible subclass is handled, eliminating the need for an else branch.

Smart Casts: Once Kotlin checks if (x is String) or when (state), it automatically casts x to String inside that block without explicit casting!

Managing Android Network State with Sealed Classes
sealed class UiState {
    object Loading : UiState()
    data class Success(val data: List<String>) : UiState()
    data class Error(val message: String) : UiState()
}

fun renderUi(state: UiState) {
    // Exhaustive pattern matching - compiler enforces all cases!
    when (state) {
        is UiState.Loading -> println("Displaying spinner...")
        is UiState.Success -> println("Rendering ${state.data.size} items.")
        is UiState.Error   -> println("Error alert: ${state.message}")
    }
}
Sealed classes guarantee that UI state transitions cannot have unhandled edge cases.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What happens if you omit one of the subclasses in a `when` expression evaluating a `sealed class` in Kotlin?