Kotlin when Statement (switch statement) Tutorial

In this section, we will learn what the when statement is and how to use it in Kotlin.

What is when Statement in Kotlin?

The when statement is like the switch statement in Java and it is used to take an argument, compare that argument with a set of cases that we define within the body of the when block and switch to the instructions of the target case that matched the input of the when statement.

Using the when statement is like working with an if statement that has multiple else if in it!

Alright, let’s see the syntax of this statement and see how we can use it practically in our programs.

Syntax of when Statement in Kotlin

This is the syntax of using the when statement in Kotlin

when (value){
    case → {
        //Instructions...
    }
    case2 →{
        //Instructions...
    }
    case_n →{
        //Instructions...
    }
    else →{
        //Instructions...
    }
}

when: in order to create a when statement, we first start with the keyword when.

(value): the pair of parentheses that comes after the keyword when is the place where we put the argument of the when statement and this argument will be matched against the cases that we put inside the when block.

{}: the pair of curly braces that comes after the when(value) defines the body of this statement and it’s the place where we define the cases.

case1, case2, case_n: each of these cases are basically an expression that result a value and that value will be matched against the input argument of the when statement. Now any of these cases that matched the argument of the when statement, its body will be executed.

{}: the pair of curly braces that comes after each case defines the body of that case and this is where we can put instructions to be executed if the case matched the input argument of the when statement.

: we use an arrow symbol to separate each case from its instructions (or its block, basically).

Note: After running the body of the case statement that matched the argument of the when statement, the rest of cases in that when block will be skipped and our program will continue to run the instructions after the body of the when block. (Unlike the switch statement in Java, we don’t need to use the break statement in every case of the when block!).

Note that if a case block in a when statement has only one expression in it, we can simply remove the curly brace of that case and put that expression right after the symbol as:

when (value){
    case → //Instruction 
    case2 →//Instruction 
    case_n →//Instruction 
    
}

Kotlin when statement with an Optional else Statement

The when block can also have an optional else statement as well!

This else statement works the same as the else statement that we put for an if statement.

Basically, the instruction of an else statement runs only if none of the cases in the target when block matched the value of that when statement.

Note: we put the else clause as the last clause of a when statement.

when (value){
    case → //Instruction 
    case2 →//Instruction 
    case_n →//Instruction 
    else →//Instruction 
}

Note that the else clause doesn’t take any argument!

Example: using when statement in Kotlin

fun main(){
    println("Please enter a value from this list: Jack, Omid, Ellen, John")
    var name = readLine() 

    when (name){
        "Jack"->println("The name is: Jack")
        "Omid"->println("The name is: Omid")
        "Ellen"->println("The name is: Ellen")
        "John"->println("The name is: John")
    }
}

Output:

Please enter a value from this list: Jack, Omid, Ellen, John

Omid

The name is: Omid

How Does the when Statement Work in Kotlin?

In the example above, we have a list of names and asked users to enter one of these names as the input for the program.

After that, the value entered by a user is passed as the argument of the when statement and the comparison between this argument and the cases of the when block now begins.

Here, the value of the first case statement didn’t match the argument and so it is passed. But the value of the second case matched the value of the argument and so the instructions within its body (which is just one single statement) now run.

After that, the rest of cases in the when block is skipped and our program will continue to run the instructions after the when block (for this particular example, we don’t have any instruction so the program terminates afterward).

Example: using else statement in the Kotlin when block

fun main(){
    println("Please enter a value from this list: Jack, Omid, Ellen, John")
    var name = readLine() 

    when (name){
        "Omid"->println("The name is: Omid")
        "Jack"->println("The name is: Jack")
        "Ellen"->println("The name is: Ellen")
        "John"->println("The name is: John")
        else->{
            println("The value of the name variable is undefined! ")
            println("Bye Bye :)")
        }
    }
}

Output:

Please enter a value from this list: Jack, Omid, Ellen, John

5

The value of the name variable is undefined!

Bye Bye 🙂

Here the value of the when statement didn’t match any value of the cases and so the instructions within the else clause ran as a result!

Kotlin when block as Expression

A when statement can act as an expression as well! This means you can expect a when statement to return a value to you! This value can then be assigned to a variable or be passed as the argument to a function, etc.

Now the value that a when statement returns is actually the last expression in the body of the case block that its value matched the argument of that when statement.

But remember: when using a when statement as an expression, we must return a value from the when block. This means either one of the case clauses must match the argument of the when statement and its last expression should match the data type of the variable that the result of the when block is about to be stored in it or there should be an else clause with its last expression result a value of the same data type as the data type of the variable that holds the result of calling the when statement.

Example: returning value from a when block in Kotlin

fun main(){
    println("Please enter a value from this list: Jack, Omid, Ellen, John")
    var name = readLine() 

    var result:String = when (name){
        "Omid"->"The name is: Omid"
        "Jack"->"The name is: Jack"
        "Ellen"->"The name is: Ellen"
        "John"->"The name is: John"
        else->{
            println("The value of the name variable is undefined! ")
            "Bye Bye :)"
        }
    }
    println(result)
}

Output:

Please enter a value from this list: Jack, Omid, Ellen, John

Ellen

The name is: Ellen

Kotlin when block with multiple values for each case

Each case in a when block can have over one value (Or basically over one expression) as their values!

In such case, Kotlin will check every value of each case clause and if one of them matched the argument of the when statement, the body of that case clause will run as a result.

Note: we use comma to separate the values of each case clause from each other.

Example: using multiple values for each case in when block

fun main(){
    println("Please enter a between 1 to 10")
    var num = readLine()?.toInt()

    var result:String = when (num){
        1,5-2,10-3->"The value is either 1, 3 or 7"
        2,4,8->"The value is either 2, 4 or 8"
        else->{
            println("OK, I gave up I don't know the value! ")
            "Bye Bye :)"
        }
    }
    println(result)
}

Output:

Please enter a between 1 to 10

4

The value is either 2, 4 or 8

Kotlin when block: in and range operator

We can also use the range and the in operator as the value for each case statement in a when block.

These two operators are especially useful when the argument of a when statement is a number and we want to know if it’s in a specific range of numbers or not.

Example: using the in and operator in the when block

fun main(){
    println("Please enter a number between 0 to 1000")
    var num = readLine()?.toInt()

    when (num){
        in 0..100-> println("The value is between 0 to 100")
        in 100..500->println("The value is between 100 to 500")
        in 500..1000->println("The value is between 500 to 1000")
        else->{
            println("You've entered a value above 1000! :(")
        }
    }
}

Output:

Please enter a number between 0 to 1000

55

The value is between 0 to 100

Kotlin when block and the is operator

We can also use the is operator as the expression for each case in a when block to see if the data type of the when’s argument is of specific type or not!

Example: when block and the is operator in Kotlin

when (x){
        is Int->println("The type of the value is Int")
        is String->println("The type of the value is String")
        is Float->println("The type of the value is Float")
        else->{
            println("We don't know the type of the value")
        }
}
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies