Kotlin when Expression

In this tutorial you will learn about the Kotlin when Expression and its application with practical example.

Kotlin when Expression

In Kotlin, when expression is considered as replacement of switch statement exists in other languages like C, C++, and Java. It is more concise yet powerful than switch statements.

Syntax:-

Using When as an Expression

In Kotlin, when can be used as an expression like the if and we can assign its result to a variable –

Example:-

Output:-

Using when Without Expression

In the above example, we used when as an expression. However, it’s not mandatory to use when as an expression.

Example:-

Output:-

Multiple when branches into one

In Kotlin, multiple branches can be combined into one as comma separated. This is helpful when you need to run a common logic for multiple cases –

Example:-

Output:-

Checking given value is in a range or not using in operator

In Kotlin, range is indicated using the (..) operator. For example, you can create a range from 1 to 5 using 1..5. The in operator allows you to check if a value belongs to a range/collection –

Example:-

Output:-

Checking given variable is of certain type or not using is operator

In Kotlin, is and !is operator can be used to check whether a value is of a particular type in runtime.

Example:-

Output:-

 

In this tutorial we have learn about the Kotlin when Expression and its application with practical example. I hope you will like this tutorial.