Sobes.tech
Middle

How to use sealed classes in Kotlin to model hierarchies?

sobes.tech AI

Answer from AI

Sealed classes are used to represent restricted inheritance hierarchies, where all possible subclasses are known at compile time.

Main features:

  • All direct subclasses must be in the same file as the sealed class (before Kotlin 1.5). Starting from Kotlin 1.5, they can be in any file of the same compilation.
  • Subclasses of a sealed class can be regular classes, data classes, object declarations, or other sealed classes.
  • The constructor of a sealed class is private by default; other modifiers (public, protected, internal) are not allowed.
  • They allow exhaustive analysis in when-expressions, which guarantees handling all possible cases and eliminates the need for an else branch.

Example of usage for modeling user interface state:

sealed class UiState {
    object Loading : UiState() // Loading state
    data class Success(val data: String) : UiState() // Successful data retrieval
    data class Error(val message: String) : UiState() // Error
}

Using in a when expression:

fun handleUiState(state: UiState): String {
    return when (state) {
        UiState.Loading -> "Loading data..."
        is UiState.Success -> "Data loaded successfully: ${state.data}"
        is UiState.Error -> "Error: ${state.message}"
    }
}

Advantages:

  • Type safety: the compiler checks that all possible subclasses are handled.
  • Readability: clearly shows what data or states are possible.
  • Convenience: simplifies working with when expressions.
How to use sealed classes in Kotlin to model… - sobes.tech