Hit enter after type your search item

Kotlin when (replacement of switch statement)

What is Kotlin when?

As a beginner, you might be looking at how Kotlin switch statement works, especially if your background is working in C, Java, etc. languages.

In Kotlin, we have no switch statement. Instead, Kotlin replaces the switch with the When expression.

Syntax and an idea how when is used in Kotlin:

A few main points about Kotlin when:
  • In Kotlin, the when can be used as an expression or statement.
  • If using ‘when’ as an expression then the satisfied branch’s value becomes the value of the overall expression.
  • In the case of using it as a statement, the values of the individual branches are ignored.
  • Just like the ‘default’ case in Java switch, the default statement is ‘else’ in case of when in Kotlin.
  • The else is mandatory if you use when as an expression.

Now, let us go through a few examples of using the when as an expression and statement.

The example of using when

In this example, we have a number variable and test the value in the ‘when’ and display a result. Five cases and an else branch is given as follows:

The output:

The value is 20

Using commas for branch conditions example

You may also combine the branch conditions by a comma; in the situation having many cases. For example:

The result:

x == 5 or x ==10 or x == 15

This can be useful if the intended output is the same for more than one branch.

The example of when as an expression

In this example, the when is used as an expression. As you run this code, the program will ask to enter the color code from the given options.

If the entered code exists the corresponding branch value is returned and displayed, otherwise, the else part executes and displays its line:

The result as I entered ‘bk’:

Kotlin when

The example of using a range in when

You may also use a range or a collection in the when in Kotlin. The example below uses a range with ‘in’ operator to check if the variable’s value is in the given range or not:

The output:

The number exists in the given range

Similarly, you may use the ‘!in’ operator to check the range or collection.

Using ‘when’ as if..else

If you use when without any expression, it acts as the if..else chain. In that case, the conditions are Boolean expression. See an example below:

The output:

Some other number!

This div height required for enabling the sticky sidebar