The Sealed Classes and when Expression
Learn how to use sealed classes with the when expression.
We'll cover the following...
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 emptyprintln(commentValue("ABC")) // Too shortprintln(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 ...