Sobes.tech
Middle

Kuidas kasutada suletud klasse hierarhiate modelleerimiseks Kotlinis?

sobes.tech AI

Vastus AI-lt

Sealed classes (sealed classes) are used to represent limited 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 (up to Kotlin 1.5). Starting from Kotlin 1.5, they can be in any file within 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 UI 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
}

Usage in 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 can be.
  • Convenience: simplifies working with when expressions.