...

/

The Sealed Classes and when Expression

The Sealed Classes and when Expression

Learn how to use sealed classes with the when expression.

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.

Press + to interact
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 ...