Search⌘ K
AI Features

The Sealed Classes and when Expression

Explore how Kotlin's sealed classes and when expressions provide controlled and exhaustive type handling. Understand their role in creating flexible, finite type hierarchies with data-rich subclasses, and learn differences compared to enums to write safer, clearer code.

The when expression

Using when as an expression must return some value, so it must be exhaustive. In most cases, the only way to achieve this is to specify an else clause.

Kotlin 1.5
fun commentValue(value: String) = when {
value.isEmpty() -> "Should not be empty"
value.length < 5 -> "Too short"
else -> "Correct"
}
fun main() {
println(commentValue("")) // Should not be empty
println(commentValue("ABC")) // Too short
println(commentValue("ABCDEF")) // Correct
}

However, there are also cases in which Kotlin knows that we have specified all possible values. For example, when we use a when expression with an enum value and ...