Sobes.tech
Middle

Are you familiar with sealed classes and what is their feature?

sobes.tech AI

Answer from AI

Yes, I am familiar.

The feature of sealed classes is that they allow you to restrict the inheritance hierarchy. All direct subclasses of a sealed class must be declared in the same file. This guarantees that the compiler knows all possible subtypes, which is useful for exhaustiveness checks in when expressions.

Example:

sealed class Result {
    data class Success(val message: String) : Result()
    data class Error(val code: Int, val description: String) : Result()
    object Loading : Result() // Singleton for loading state
}

fun processResult(result: Result) {
    when (result) {
        is Result.Success -> println("Success: ${result.message}")
        is Result.Error -> println("Error ${result.code}: ${result.description}")
        Result.Loading -> println("Loading...")
        // No need for an else branch, as the compiler knows all options
    }
}

Advantages:

  • Safety: Guaranteed exhaustiveness of when expressions without needing an else.
  • Readability: Clearly indicates a limited set of possible states or subtypes.
  • Control: Prevents uncontrolled inheritance from outside.

Difference from enum class: sealed classes can have different data types for each subtype (like Success and Error in the example), whereas elements of enum class are static and can only have certain properties common to all. sealed classes can also have object instances (Loading).

Are you familiar with sealed classes and what is… - sobes.tech