Sobes.tech
Middle

What are the limitations of sealed classes in Kotlin?

sobes.tech AI

Answer from AI

Sealed classes in Kotlin have the following restrictions:

  • All subclasses of a sealed class must be declared in the same file as the sealed class itself. This restriction ensures complete control over the inheritance hierarchy.
  • A sealed class cannot be open for inheritance outside the file where it is declared.
  • Sealed classes cannot be abstract, but they are abstract by themselves (you cannot instantiate them).
  • Unlike enum classes, sealed classes can have different types of subclasses with their own properties and methods.

Example of using a sealed class with a when expression, where the compiler checks for exhaustiveness:

sealed class Result
class Success(val data: String) : Result()
class Error(val error: Throwable) : Result()

fun handleResult(result: Result) {
    when(result) {
        is Success -> println("Data: ${result.data}")
        is Error -> println("Error: ${result.error.message}")
        // No else, as all subclasses are covered
    }
}
What are the limitations of sealed classes in Kotlin… - sobes.tech