Sobes.tech
Junior — Middle

In what cases and where should you use sealed class declaration?

sobes.tech AI

Answer from AI

sealed class in Kotlin is used when you want to restrict the inheritance hierarchy to a specific set of subclasses. It is useful when all possible variants are known in advance and should be limited in one place.

Use cases include:

  • Representing states in UI (State pattern)
  • Describing operation results (success, error, loading)
  • Handling events with known types

Example:

sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val error: Throwable) : Result()
    object Loading : Result()
}

Here, Result limits the variants of the result, making it easier to handle with when without an else branch.