When Expressions
Using the When expression
By: King When Expressions are similar to If Expressions. It matches its argument against all branches from top to bottom until a specific condition is met.

Syntax

when ([value]) {

[match_condition_1] -> { }
[match_condition_2] -> { }
...
else -> { }

}

Examples

val number = 10;

when(number){
5 -> println("Number is 5")
else -> println("Number is not 5.")
}

In the above example, the When Expression has a two branches - (5) and (else). It will compare the value of the argument with 5 first, and if it equals 5, it will print the message - "Number is 5." If not, it will move on and execute the print statement in the else branch.

val number = 8

when(number){
5, 10, 15 -> println("Number is either 5, 10, or 15");
}

In this example, a single branch has multiple match conditions - (5, 10, 15).

Although having the ability to add multiple match conditions in a branch, sometimes it may not be enough. What if we want to execute some code it the number is between 1 and 100? If we use the above example, we will have a branch similar to:

1, 2, 3, 4, 5, 6, 7,8 ...., 100 -> ...

Instead of specifying the numbers manually, we can use a Range.

Instead of specifying the numbers manually, we can use a Range (a..b) instead. To use a range, we need to use the in or !in operator.

val number = 10

when(number) {
in 0..10 -> println("Number is between 0 and 10")
in 20..30 -> println("Number is between 20 and 30")
!in 10..20 -> println("Number is NOT in 20 to 30")
else -> println("Other")
}

Executing Multiple Statements

We can also execute multiple statements in a branch. To do this, add the opened and closed curly brackets at the end of the arrow to indicate that there will be a block of statements we want to perform.

when(fruit) {

"Apple" -> {

}
"Banana" -> { .. }
"Cherry" -> { ... }
}

When Expressions That Returns a Value

When Expressions can also return a value, that is why it is called the "When Expression."

When Expressions that returns a value, must have a ELSE branch and the last statement of the branch must be the value that it is returning.

val result = when(number) {

in 1..10 -> {
val a = 10
val b = 20
a * b * number
}
else -> {
val a = 10
val b = 20
a / b / number
}

}