When Keyword in Kotlin

You are here:
Estimated reading time: 3 min

In this tutorial, we will learn how to use when keyword in Kotlin. We will also cover the following topics:

  • Using when with/without arguments
  • when as an expression
  • when as a statement
  • Smart Casts with when

Syntax

when(argument){
    condition1 -> statement1
    condition2 -> statement2
    condition3 -> statement3
    else -> statement
}

A when block has an argument and several branches.

Each branch has a condition on the left-hand side and a statement on the right-hand side which is executed if the condition is satisfied.

The argument is checked with each branch. If a branch’s condition is satisfied, its statement is executed and control is shifted to outside the when block.

If none of the branches’ conditions are satisfied, then, the else statement is executed and after that, control is shifted to outside the when block. This else statement represents the default statement in the switch-case operator.

If 2 conditions yield the same output, they can be grouped together using comma(,) as shown below:

when(argument){
    condition1,condition2 -> statement1
    condition3,condition4 -> statement2
    condition5 -> statement3
    else -> statement
}

When can be used either with or without an argument.

If used with an argument, when replaces the switch-case operator found in languages like Java, C, etc.

If used without an argument, when replaces the if-else-if chain.

Using when with an argument

When used with an argument, when compares the passed argument with all the branches sequentially until some branch’s condition is satisfied.

A branch represents a single condition (a case in the switch-case operator).

when may have as many number of branches, as desired, wherein each branch represents a different condition/case.

when(arg){
    0 -> print("arg = 0")
    1,3,5,7 -> print("arg is odd")
    2,4,6,8 -> print("arg is even")
    else -> print("arg value out of range")
}

Using when without an argument

When used without an argument, when acts as a replacement for an if-else-if chain.

If no argument is given, the branches in when are considered as simple Boolean expressions.

If for a branch, the condition yields true, that branch is executed, and control is shifted to the statement after the when block.

If false, the next branch is checked until all branches are over.

var arg=15
when{
    arg < 10 -> print("Poor")
    arg in 10..20 -> print("Average")
    arg in 21..30 -> print("Good")
    else -> "Invalid Rating"
}

In Kotlin, when can be used as an expression, as well as a statement.

If used as an expression, when returns a value.

And if used as a statement, it works like a traditional switch-case operator.

To know more about the difference between an expression and a statement: https://blog.kotlin-academy.com/kotlin-programmer-dictionary-statement-vs-expression-e6743ba1aaa0

When as an expression (returns some value)

when can be used as an expression and its value can be assigned to a variable, as shown in the example below:

var planetName=when(planetNumber){
    1 -> "Mercury"
    2 -> "Venus"
    3 -> "Earth"
    4 -> "Mars"
    5 -> "Jupiter"
    6 -> "Saturn"
    7 -> "Uranus"
    8 -> "Neptune"
    else -> "Invalid planet number."
}

In the above example, the argument for when is planetNumber and the returned value from when is assigned to the variable planetName.

For example, if the planetNumber is 4, then the value in the planetName variable after when is executed will be “Mars”.

Note: If when is used as an expression, else statement is compulsory. (If when covers all possible values of the argument, then else statement is not necessary.)

When as a statement (like switch-case)

when can be used as a statement. The passed argument is checked with all branches of the when block and if a condition is satisfied, that branch is executed and control is shifted to the statement after the when block.

If none of the branches’ conditions are satisfied, then the control simply moves to the next statement after the when block without executing any of the branches of the when block.

when(x){
    1 -> print("Hello")
    2 -> print("Goodbye")
    else -> print("Something's wrong")
}
print("Outside when")

In the above example, if the value of x is 1, the output will be:

Hello

Outside when

If the value of x is neither 1 nor 2, the output will be:

Something’s wrong

Outside when

Usage

Check if the input value is within range or not

in or !in operator can be used to check whether the argument value falls within a range or not.

(in operator in Kotlin is used to check if a variable is in a collection/range or not. If a variable is present in a range/collection, it returns true. If a variable is not in the range/collection, false is returned.)

fun main(){
    var num=12
    when(num){
        in 1..10 -> println("First 10")
        in 11..20 -> println("10 to 20")
        else -> println("Out of range")
    }
}

Check if the input value is of a certain type (Smart Casts with when)

is or !is operator can be used to check whether a given variable is of a certain type or not. For example, “is Int” will return true if the variable is an integer, else false will be returned.

fun main(){
    var num=12
    when(num){
        is Int-> println("I am an Integer")
        is Double -> println("I have a Decimal Point")
        is String -> println("I am made of characters")
        is IntArray -> println(num.sum())
    }
}

Branches with multiple statements

Branches in when may have several statements to be executed if a condition is true, instead of just one. In such a case, curly braces are used.

fun main(){
    var num=1
    when(num){
        1 -> {
            println("January")
            println("First Month of the year")
        }
        10 -> {
            println("October")
            println("Happy Halloween")
        }
        12 -> {
            println("December")
            println("Merry Christmas!")
        }
    }
}

Sources

https://kotlinlang.org/docs/reference/control-flow.html

https://en.wikipedia.org/wiki/Kotlin_(programming_language)

To learn more about control flow in Kotlin, check out our list of articles :

For Loops in Kotlin

While Loops in Kotlin

If Expression in Kotlin

Was this article helpful?
Dislike 0
Views: 18