Kotlin when expression

03 Jan, 2022
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 
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
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
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
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
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
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->"February"        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
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
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 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
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 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 != 0fun 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) = 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
clintra
rajeev0719singh
mssoni916
Kotlin Control-flow
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Higher-Order Functions
Suspend Function In Kotlin Coroutines
How to Communicate Between Fragments in Android?
Android Menus
Spinner in Kotlin
MVP (Model View Presenter) Architecture Pattern in Android with Example
Kotlin extension function