Sobes.tech
Junior — Middle

Can you explain how sealed classes work in Kotlin or a similar language?

sobes.tech AI

Answer from AI

Sealed class in Kotlin is a special type of class that restricts inheritance. All subclasses of a sealed class 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 example, in when expressions without the need to write else.

Example:

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

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

This approach helps make the code safer and more convenient for handling a limited set of options.

Can you explain how sealed classes work in Kotlin or… - sobes.tech