Kotlin When Expression

In this article, you will learn about when expression in Kotlin with the help of various examples.

In Kotlin, when replaces the switch operator of other languages like Java, C, C++, etc.

when matches its argument against all branches sequentially until some branch condition is satisfied.

After the first match found, it reaches to end of the when block and executes the code next to when block.

In case, if none of the branch conditions are satisfied then it will execute the else branch.

Unlike switch cases in java or any other programming language, we do not require break statement at the end of each case.

In Kotlin, when can be used in two ways:

  • when as a statement
  • when as an expression

Using when as a Statement

Using when as a statement, the values/conditions of all individual branches are compared sequentially with the when argument and execute the corresponding branch where condition matches.

If none of the branches satisfied with the condition then it will execute the else branch.

Note: when can be used as a statement with or without else branch.

Example 

fun main(args:Array<String>) {

   //getting input from user
    var reader = Scanner(System.`in`)
    print("Enter a number between 1 to 7: ")
    var day = reader.nextInt()

   //when statement
    when (day) {
        1 -> println("Monday")
        2 -> println("Tuesday")
        3 -> println("Wednesday")
        4 -> println("Thursday")
        5 -> println("Friday")
        6 -> println("Saturday")
        7 -> println("Sunday")
        else -> println("Invalid day")
    }    
}

Output

Enter a number between 1 to 7: 5
Friday

Note: If you want to give more than one statement inside a branch then you must enclose it inside curly braces.

Example explained

In the above example, when day = 5: 

  • the value 5 is checked, yields true and “Friday” gets printed.

  when x=8:

  • none of the branches satisfied with the condition, execute else branch and “Invalid day” gets printed.

Using when as an Expression

Using when as an expression or when expression, returns a value, that we can store it in a variable and use it.

If when is used as an expression, the value of the satisfied branch becomes the value of the overall expression.

If none of the branch conditions are satisfied with the argument, the else branch is executed.

Note: It is mandatory to use else branch while using when as an expression.

Example 

fun main(args: Array<String>) {
   
    //getting input from user
    var reader = Scanner(System.`in`)
    print("Enter a number between 1 to 7: ")
    var day = reader.nextInt()
    
    //when expression
    var dayName = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        4 -> "Thursday"
        5 -> "Friday"
        6 -> "Saturday"
        7 -> "Sunday"
        else -> println("Invalid day")

    }
    println("The Name of the day of the week is : $dayName")
}

Output

Enter a number between 1 to 7: 4
The Name of the day of the week is : Thursday

Example explained

In the above example, when day = 4:

  • the value 4 is checked, yields true and “Thursday” is assigned to dayName variable and gets printed.

  when x=8:

  • none of the branches satisfied with the condition, execute else branch and “Invalid day” is assigned to dayName variable and gets printed.

 

There are different ways to use when block in Kotlin:

Combine two or more branch conditions with a comma 

We can use multiple branches in a single one separated by a comma.

When common logic is shared by some branches then we can combine them in a single branch.

Example

fun main(args: Array<String>) {
    
    //getting input from user
    var reader = Scanner(System.`in`)
    print("Enter a number between 1 to 10: ")
    var num = reader.nextInt()
     
    when (num) {
        2, 4, 6, 8 -> println("$num is an even number less than 10.")
        1, 3, 5, 7, 9 -> println("$num is an odd number less than 10.")
        else -> println("Invalid number")
    }
}

Output

Enter a number between 1 to 10: 5
5 is an odd number less than 10.

Check the input value in a range or not 

To check whether the argument passed in when block exists in particular Range or not, we can use in or !in operator.

If the argument lies in a particular range then in operator returns true and if the argument does not lie in particular range then !in returns true.

Example

fun main(args: Array<String>) {

    var number = 14
    when (number) {
        in 1..10 -> println("Input is provided in the range 1 to 10")
        in 11..20 -> println("Input is provided in the range 11 to 20")
        !in 1..20 -> println("Input is not provided in the range 1 to 20")
    }
}

Output

Input is provided in the range 11 to 20

Check given variable is of a certain type or not 

To check whether a value is of a particular type in runtime, we can use is or !is operator.

 For example, If the variable is Integer type then is Int returns true else return false.

Example

fun main(args: Array<String>) {
    var num: Any = "Welcome to C1CTech"

    when(num){
        is Int -> println("It is an Integer")
        is String -> println("It is a String")
        is Double -> println("It is a Double")
    }
}

Output

It is a String

Using when as a replacement for an if-else-if chain 

We can use when as a replacement for if-else-if.

If no argument is supplied then the branch conditions are simply boolean expressions, and a branch is executed only when its condition is true:

Example

fun main(args: Array<String>) {
    
   val marks = 65

    when {
        marks >= 80 -> println("You got A+ grade")
        marks >= 75 -> println("You got A grade")
        marks >= 60 -> println("You got B grade")
        marks >= 45 -> println("You got C grade")
        marks >= 35 -> println("You got D grade")
        else -> println("You are fail")
    }

}

Output

You got B grade

 

Leave a Reply