Sobes.tech
Junior — Middle

Is it possible to use the 'when' operator to handle not all subclasses of a sealed class?

sobes.tech AI

Answer from AI

In Kotlin, if you have a sealed class, the when operator can be used without an else branch when checking all its subclasses, because the compiler knows all possible options. However, if you do not handle all subclasses of the sealed class in when, the compiler will require you to add an else branch to handle the missed cases.

That is, you can use when to handle not all subclasses, but then an else branch is mandatory.

Example:

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

fun handle(result: Result) {
    when (result) {
        is Result.Success -> println("Success: ${result.data}")
        else -> println("Something else") // mandatory if not all subclasses are handled
    }
}

If all subclasses are handled, else is not needed.