Javatpoint Logo
Javatpoint Logo

Kotlin when Expression

Kotlin, when expression is a conditional expression which returns the value. Kotlin, when expression is replacement of switch statement. Kotlin, when expression works as a switch statement of other language (Java, C++, C).

Using when as an Expression

Let's see a simple example of when expression.

Output:

You provide Four

Using when Without Expression

It is not mandatory to use when as an expression, it can be used as normally as it used in other language.

For Example

Output:

Four

Multiple Statement of when Using Braces

We can use multiple statement enclosed within block of condition.

For Example

Output:

Monday
First day of the week

Multiple branches of when

We can use multiple branches of condition separated with a comma. It is used, when we need to run a same logic for multiple choices.

Output:

It is rainy season

Using when in the range

The when expression also check the ranges of input provided in when condition. A range is created using .. (double dot) operator. The in operator is used to check if a value belongs to a range.

For Example:

Output:

Input is provided in the range 6 to 10

Next TopicKotlin for Loop




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA