A typical switch is essentially just a declaration that can substitute a series of if / else statements that are underlying. It can not replace all kinds of if / else sequences, however, but only those that compare a value to a certain constant. So, you can only use a switch to perform an operation if one particular variable has a certain accurate value. As in the example which follows:
|
|
In Kotlin, ‘when’ block replaces the switch operator with other languages such as Java. ‘When’ block is normally used when a certain block of code needs to be executed when any condition is satisfied. The statement of when expression is compared one by one with all branches before some match is found. It reaches the end of the when block after the first match has been identified, and executes the code next to when block. Unlike switch case in java or any other programming language, at the end of each case we don’t need a break sentence.
In Kotlin, ‘when’ can be used in two ways:
- when as a statement
- when as an expression
Using when as a statement with else
When block can be used with or without else branch. If ‘when’ block is used as a statement, the values of all branches are sequentially compared with the argument, and the corresponding branch is executed where the condition matches. If none of the branches are satisfied with the condition then the other branch is executed.
|
|
Using when as a statement without else
When block can be used with or without else branch. If used as a statement, the values of all branches are sequentially compared with the argument, and the corresponding branch is executed where the condition matches. If none of the branches are satisfied with the condition then none of the branch gets executed and it simply exits the ‘When’ block
|
|
Using when as an expression
If used as an expression, the value of the branch to which condition satisfied will be the overall expression value. As an expression ‘when’ block returns a value that fits the statement, and we can store it directly in a variable or print.
|
|
If the argument doesn’t satisfy any of the branch conditions, the else branch is executed. The else branch is mandatory as an expression, unless the compiler can prove that branch conditions cover all possible cases. If we can’t use else branch, a compiler error will be thrown.
‘when’ expression must be exhaustive, add necessary ’else’ branch
Combine multiple branches in one using comma
We can use multiple branches separated by a comma in a single one. If some branches share similar logic then we can combine them in a single branch
|
|
Check the input value in range or not
Using the ‘in’ or ‘!in’ we can check the range of arguments passed in ‘when’ block in the Operator. The Kotlin operator ‘in’ is used to verify the presence of a given variable or property within a range. If the argument lies within a given range then it returns true in the operator and if the argument does not lie within the range then !in returns true
|
|