Kotlin When Expression

Kotlin when expression is used when you have to match the value of an expression to a set of values and execute a block of statement corresponding to the matched value.

Kotlin when expression can be related to switch case in Java, but when expression is concise in syntax and extended in functionality.

In this tutorial, we will learn the syntax of Kotlin when expression, and how to use it in a Kotlin application with example programs.

Using object type of Any with when expression makes is really broad in the usage, where the matching can be done for int, string or any other primitive datatype. We shall learn in detail in our second example.

Syntax of Kotlin When statement

Let us see terminology and working of When expression.

Following is the syntax of Kotlin when expression.

In the above code snippet, 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 no match happens, and there is an else block is provided inside the when expression, 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. And the program control comes out of the when expression.

Example – Kotlin When Expression

Following is a simple example for when expression in Kotlin. In the when expression, based on the value of n (nth day of week), we shall print the day of week.

Run the above program in your IDE, and you shall get the following output printed to console.

For the function call, printWeekDay(12), there is no match found. Hence, else block is executed.

Example – Kotlin When with object of type Any

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.

Run the Kotlin program and you shall get the following output in console.

Conclusion

In this Kotlin Tutorial, we have learnt the syntax of Kotlin When and how to use it in Kotlin for decision making tasks.