Understanding when expression in Kotlin with examples

when expression in Kotlin programming language is kind of switch case in Java, but concise in syntax, extended in functionality and more fun. Using “Any” object type with when expression makes is really broad in the usage.

Let us see terminology and working of when expression.

Syntax of when expression in  Kotlin - Kotlin Tutorial - www.tutorialkart.com

Syntax of when expression in Kotlin

In the above picture, the expression in the parenthesis next to the “when” keyword is evaluated to a value. The value is matched against the values(value_1, value_2, . . ) written inside the block. When a match happens, the corresponding branch is executed. If an else block is provided inside the when expression, and when no match is happened, the branch corresponding to the else block is executed.

Note : When there are more than one values that match to the expression’s value, only the branch corresponding to first match is executed.

Now we shall a simple example of when expression in Kotlin programming language.

Example of when expression in Kotlin programming language :

Output :

Example of when expression with variable in expression of “Any” object type in the expression :

In this example, the variable in the expression is of type “Any”. The variable can be matched with values of any type. The variable n, is matched against values of type Int and String. This could be extended to any of the primitive data types.
 

Output :