Open In App

Kotlin when expression

Last Updated : 30 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 is found, it reaches to end of the when block and executes the code next to the when block. Unlike switch cases in Java or any other programming language, we do not require a 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 the condition matches. If none of the branches is satisfied with the condition then it will execute the else branch.  

Kotlin




fun main (args : Array<String>) {
    print("Enter the name of heavenly body: ")
    var name= readLine()!!.toString()
    when(name) {
        "Sun" -> print("Sun is a Star")
        "Moon" -> print("Moon is a Satellite")
        "Earth" -> print("Earth is a planet")
        else -> print("I don't know anything about it")
    }
}


Output: 

Enter the name of heavenly body: Sun
Sun is a Star
Enter the name of heavenly body: 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 are satisfied with the condition then it simply exits the block without printing anything to system output. 

Kotlin




fun main (args : Array<String>) {
    print("Enter the name of heavenly body: ")
    var name= readLine()!!.toString()
    when(name) {
        "Sun" -> print("Sun is a Star")
        "Moon" -> print("Moon is a Satellite")
        "Earth" -> print("Earth is a planet")
         
    }
}


Output: 

Enter the name of heavenly body: : 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. 

Kotlin




fun main(args : Array<String>) {
    print("Enter number of the Month: ")
    var monthOfYear  = readLine()!!.toInt()
    var month= when(monthOfYear) {
        1->"January"
        2->"February"
        3->"March"
        4->"April"
        5->"May"
        6->"June"
        7->"July"
        8->"August"
        9->"September"
        10->"October"
        11->"November"
        12->"December"
        else-> "Not a month of year"
    }
    print(month)
}


Output: 

Enter number of the Month: 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 the 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 large body is a planet or not, so we combined all the names of planets in a single branch. Anything entered other than planet name will execute the else branch.  

Kotlin




fun main (args :Array<String>) {
    print("Enter name of the planet: ")
    var name=readLine()!!.toString()
    when(name) {
        "Mercury","Earth","Mars","Jupiter"
            ,"Neptune","Saturn","Venus","Uranus" -> print("This is a planet")
        else -> print("This not a planet")
    }
}


Output: 

Enter name of the planet: Earth
Planet

Check the input value in the range or not:

Using the in or !in operator, we can check the range of argument passed in when block. ‘in’ operator in Kotlin is used to check the existence of a particular variable or property in a range. If the argument lies in a particular range then in operator returns true and if the argument does not lie in a particular range then !in returns true.  

Kotlin




fun main (args:Array<String>) {
    print("Enter the month number of year: ")
    var num= readLine()!!.toInt()
    when(num) {
        in 1..3 -> print("Spring season")
        in 4..6 -> print("Summer season")
        in 7..8 -> print("Rainy season")
        in 9..10 -> print("Autumn season")
        in 11..12 -> print("Winter season")
        !in 1..12 -> print("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 a certain type or not:

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

Kotlin




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 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: 

Kotlin




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 a 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 the Boolean value true else return false. 

Kotlin




fun hasPrefix(company: Any):Boolean{
return 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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads