Skip to content
Related Articles

Related Articles

Kotlin when expression
  • Last Updated : 16 May, 2019

In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match found, it reaches to end of the when block and execute the code next to when block. Unlike switch case 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 with else

when can be used as a statement with or without else branch. If it is used as a statement, the values of all individual branches are compared sequentially with the 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.




import java.util.Scanner;
fun main(args: Array<String>) {
    var reader = Scanner(System.`in`)
    print("Enter any largebody:")
    var lb = reader.next()
  
    when(lb) {
        "Sun" -> println("Sun is a Star")
        "Moon" -> println("Moon is a Satellite")
        "Earth" -> println("Earth is a planet")
         else -> println("I don't know anything about it")
    }
}

Output:

Enter any largebody: Sun
Sun is a Star

Enter any largebody: Mars
I don't know anything about it

Using when as a statement without else

We can use when as a statement without else branch. If it is used as a statement, the values of all individual branches are compared sequentially with the argument and execute the corresponding branch where condition matches. If none of the branches satisfied with the condition then it simply exits the block without printing anything to system output.






import java.util.Scanner;
fun main(args: Array<String>) {
    var reader = Scanner(System.`in`)
    print("Enter name:")
    var lb = reader.next()
  
    when(lb) {
        "Sun" -> println("Sun is a Star")
        "Moon" -> println("Moon is a Satellite")
        "Earth" -> println("Earth is a planet")
    }
}

Output:

Enter name: Mars

Process finished with exit code 0

Using when as an expression –

If it is used as an expression, the value of the branch with which condition satisfied will be the value of overall expression. As an expression when returns a value with which the argument matches and we can store it in a variable or print directly.




import java.util.Scanner;
fun main(args: Array<String>) {
    var reader = Scanner(System.`in`)
    print("Enter the month number:")
    var monthOfYear = reader.nextInt()
    var month = when(monthOfYear){
        1->"January"
        2->"Febuary"
        3->"March"
        4->"April"
        5->"May"
        6->"June"
        7->"July"
        8->"August"
        9->"September"
        10->"October"
        11->"November"
        12->"December"
        else -> {
            println("Not a month of year")
        }
    }
    println(month)
}

Output:

Enter the month number:8
August

If none of the branch conditions are satisfied with the argument, the else branch is executed. As an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions. If we cannot use else branch it will give a compiler error.

Error:(6, 17) Kotlin: 'when' expression must be exhaustive, add necessary 'else' branch

Different ways to use when block in Kotlin:

Combine multiple branches in one using 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. In the example below, we need to check the entered largebody is planet or not, so we combined all the names of planet in a single branch. Anything entered other than planet name will execute the else branch.




import java.util.Scanner;
fun main(args: Array<String>) {
    var reader = Scanner(System.`in`)
    print("Enter name of planet: ")
    var name = reader.next()
    when(name) {
        "Mercury","Earth","Mars","Jupiter"
            ,"Neptune","Saturn","Venus","Uranus" -> println("Planet")
        else -> println("Neither planet nor star")
    }
}

Output:

Enter name of planet: Earth
Planet

 
Check the input value in range or not –
Using the in or !in operator we can check the range of argument passed in when block. ‘in’ operator in Koltin is used to check the existence of particular variable or property in a range. If the argument lies in a particular range then in operator return true and if the argument does not lies in particular range then !in returns true.




import java.util.Scanner;
fun main(args: Array<String>) {
    var reader = Scanner(System.`in`)
    print("Enter the month number of year: ")
    var num = reader.nextInt()
    when(num){
        in 1..3 -> println("It is spring season")
        in 4..6 -> println("It is summer season")
        in 7..8 ->println("It is rainy season")
        in 9..10 -> println("It is autumn season")
        in 11..12 -> println("It is winter season")
        !in 1..12 ->println("Enter valid month of year")
    }
}

Output:

Enter the month number of year: 5
It is summer season

Enter the month number of year: 14
Enter valid month of year

 
Check given variable is of certain type or not –
Using is or !is operator we can check the type of variable passed as argument in when block. If the variable is Integer type then is Int returns true else return false.




fun main(args: Array<String>) {
    var num: Any = "GeeksforGeeks"
    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 replacement for an if-else-if chain
We can use when as 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:




fun isOdd(x: Int) = x % 2 != 0
fun isEven(x: Int) = x % 2 == 0
  
fun main(args: Array<String>) {
    var num = 8
    when{
        isOdd(num) ->println("Odd")
        isEven(num) -> println("Even")
        else -> println("Neither even nor odd")
    }
}

Output:

Even

 
Check that a string contains particular prefix or suffix –
We can also check prefix or suffix in a given string by the below method. If the string contains the prefix or suffix then it will return Boolean value true else return false.




fun hasPrefix(company: Any) = when (company) {
    is String -> company.startsWith("GeeksforGeeks")
    else -> false
}
  
fun main(args: Array<String>) {
    var company = "GeeksforGeeks a computer science portal"
    var result = hasPrefix(company)
    if(result) {
        println("Yes, string started with GeeksforGeeks")
    }
    else {
        println("No, String does not started with GeeksforGeeks")
    }
}

Output:

Yes, string started with GeeksforGeeks
My Personal Notes arrow_drop_up
Recommended Articles
Page :