When Expressions are similar to If Expressions. It matches its argument against all branches from top to bottom until a specific condition is met.
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]) {
Examples
val number = 10;
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.
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:
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
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) {
When Expressions That Returns a Value
When Expressions can also return a value, that is why it is called the "When Expression."
val result = when(number) {