Sobes.tech
Junior — Middle

In which cases is it preferable to use a sealed class instead of an enum in Kotlin?

sobes.tech AI

Answer from AI

A sealed class in Kotlin is preferable to an enum when you need to describe a limited set of types with different data structures and behaviors, rather than just a set of constants.

Differences and when to use a sealed class:

  • Different data for each variant: In an enum, all elements are the same type of constants, whereas a sealed class allows each subclass to have its own properties and methods.
  • Inheritance and extensibility: A sealed class is a base class with a limited number of subclasses, which is convenient for expressing hierarchies.
  • Use in when: The compiler checks for exhaustiveness in when expressions with sealed classes, increasing safety.

Example of a sealed class:

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

fun handleResult(result: Result) {
    when(result) {
        is Result.Success -> println("Data: ${result.data}")
        is Result.Error -> println("Error: ${result.error.message}")
        Result.Loading -> println("Loading...")
    }
}

If you just need a fixed set of constants without data, an enum is simpler and more efficient.