Sobes.tech
Junior — Middle

What are the limitations of using a sealed class in a programming language?

sobes.tech AI

Answer from AI

Sealed classes in Kotlin are limited in that all their subclasses must be declared in the same file as the sealed class itself. This allows the compiler to know all possible subclasses and use this for exhaustiveness checking in when expressions.

Also, sealed classes cannot be open for inheritance outside the file, which limits extensibility but increases safety and predictability of the code.

Example:

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

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

Thus, sealed classes are convenient for modeling limited sets of states, but are not suitable if you need to extend the hierarchy across different modules.