In the preceding examples, the first example is the most basic when statement; we are directly comparing x’s value to 12 and 4, and if no conditions match, we are simply executing the else statement. It is like an if else if else statement.
In the second example, we check whether x lies between 1 to 10 in the first statement inside the when block, and in the second statement, we check whether x does not lie between 1 to 10. That's how we work with ranges in when. Basically, in when, we can check whether x lies in a range or exists in a collection using the in keyword. The syntax is as follows:
when(x) {
In collection_or_range -> // do something
}
In the third example, we use a function to check whether x equals the value of the expression magicNum(x). So we can also use expressions and functions in place of constants and ranges to compare x.
In the fourth example, we explore the power of the when statement using a data class instead of a primitive data type in when. Note how we are able to access all properties of x inside when and also play with them.