When expression in Kotlin

In Kotlin, the when statement can also be used as an expression that returns a value. This is known as the when expression. The syntax is similar to the when statement, but with an added = sign after the value being matched, and each branch must return a value of the same type.

The general syntax of a when expression is:

val result = when (value) {
    pattern1 -> value1
    pattern2 -> value2
    // more patterns and values
    else -> defaultValue

In this syntax, value is the value to be matched against the patterns. Each pattern is specified using the -> symbol, and is followed by a value to be returned if the pattern matches. If no patterns match, the else block returns a default value.

Here’s an example of a when expression that returns a string:

val x = 5
val message = when (x) {
    1 -> "One"
    2 -> "Two"
    3, 4 -> "Three or Four"
    in 5..10 -> "Between Five and Ten"
    else -> "Not a valid number"


In this example, the value of x is matched against several patterns, and the corresponding string value is returned as the value of the message variable. The println statement then prints the value of message.

Note that the when expression must always have a default value specified using the else block, since otherwise it wouldn’t be possible to guarantee that the expression will always return a value.