Sobes.tech
Middle

What are sealed classes and what is their purpose?

sobes.tech AI

Answer from AI

Sealed classes represent restricted class hierarchies. They are used to represent a limited set of possible states or values.

Main features and purpose:

  • Restricted hierarchy: In Kotlin versions before 1.5, subclasses of a sealed class must be declared in the same file or nested within the sealed class. From version 1.5 onwards, this restriction is relaxed: subclasses can be in any file within the same package.
  • Enum classes with state: Unlike enum classes, each subclass of a sealed class can have its own state and behavior.
  • Exhaustive when: The compiler guarantees that a when block for an instance of a sealed class is exhaustive (all cases are covered) if no else branch is specified. This reduces the likelihood of runtime errors.

Example:

sealed class Result<out T> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
    object Loading : Result<Nothing>() // Singleton instance
}

fun processResult(result: Result<String>) {
    when (result) {
        is Result.Success -> {
            // Handle success
            println("Data: ${result.data}")
        }
        is Result.Error -> {
            // Handle error
            println("Error: ${result.exception.message}")
        }
        Result.Loading -> {
            // Handle loading state
            println("Loading data...")
        }
        // No else branch needed, as all subclasses are handled by the compiler
    }
}

Purpose:

  • Safe representation of states: Reliably represent a finite number of states, such as the result of a network request (Success, Error, Loading).
  • Improved code readability: Make code more explicit when handling different cases.
  • Increased reliability of when expressions: The compiler helps avoid unhandled cases.
  • Replacement for enum classes with state: When it is necessary to associate data with specific "variants" of an enumeration.

Thus, sealed classes provide a flexible way to model finite sets of values with the ability to store specific data for each value, while ensuring safety and clarity when processing these values in when expressions.