Ebooks

Kotlin when expression

Kotlin when expression tutorial shows how to use when expressions in Kotlin. A when expression is a replacement of a switch statement known from C family of languages.

Kotlin is a statically-typed programming language that runs on the Java virtual machine.

Kotlin when matches its argument against all branches sequentially until some branch condition is satisfied. It can be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression.

Kotlin when simple example

The following is a simple example which uses when expression with days of week.

day_of_week.kt
package com.zetcode

fun main() {

    val dayOfWeek = 3

    when (dayOfWeek) {
        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")
    }
}

In the example, we print the day of week based on an integer value. Seven different brances are tested sequentially. If one of them is satisfied, the rest are skipped. If none of them is satisfied, the else branch is executed.

Kotlin when grouping values

It is possible to group values in branches with the comma operator.

day_of_week2.kt
package com.zetcode

fun main() {

    val dayOfWeek = 5

    when (dayOfWeek){
        1,2,3,4,5 -> println("weekday")
        6,7 -> println("weekend")
        else -> println("wrong value")
    }
}

In the example, we group values to form two branches: for weekdays and for weekend.

Kotlin when expression example

Kotlin when can be used as an expression. The value of the satisfied branch is returned.

when_expression.kt
package com.zetcode

import java.time.DayOfWeek
import java.time.LocalDate

fun main() {

    val dayOfWeek: DayOfWeek = LocalDate.now().dayOfWeek

    val msg:String = when (dayOfWeek) {
        DayOfWeek.MONDAY -> "It is monday"
        DayOfWeek.TUESDAY -> "It is tuesday"
        DayOfWeek.WEDNESDAY -> "It is tuesday"
        DayOfWeek.THURSDAY -> "It is tuesday"
        DayOfWeek.FRIDAY -> "It is tuesday"
        DayOfWeek.SATURDAY -> "It is tuesday"
        DayOfWeek.SUNDAY -> "It is tuesday"
        else -> "Invalid day of week"
    }

    println(msg)
}

We determine the current weekday. The string from the matched branch is assigned to the msg variable, which is later printed to the console.

Kotlin when ranges

We can test ranges of values in when branches. (This can be done also with collections.)

age_groups.kt
package com.zetcode

fun main() {

    val age = 40

    when (age) {
        in 0..14 -> println("children")
        in 15..24 -> println("youth")
        in 25..64 -> println("adults")
        in 65..120 -> println("seniors")
        in 120..130 -> println("unlikely age")
        else -> println("wrong age value")
    }
}

We have an age variable. We assign the value to an age group using Kotlin ranges.

Kotlin when enums

Kotlin when expression can be used with enums.

when_enums.kt
package com.zetcode

enum class Season {
    SPRING, SUMMER, AUTUMN, WINTER
}

fun main() {

    val season = Season.SUMMER

    when (season) {

        Season.SPRING -> println("It is spring")
        Season.SUMMER -> println("It is summer")
        Season.AUTUMN -> println("It is autumn")
        Season.WINTER -> println("It is winter")
    }
}

We have a Season enum. We pass the enum as the argument of the when expression.

Kotlin when without argument

Kotlin when expression can be used without an argument.

random_val.kt
package com.zetcode

import java.util.Random

fun main() {

    val r:Int = Random().nextInt(10) - 5

    when {
        r < 0 -> println("negative value")
        r == 0 -> println("zero")
        r > 0 -> println("positive value")
    }
}

In the example, we generate a random value. We test the value with the when expression without passing it as an argument in round brackets.

Kotlin when types

We can check for types with the is operator.

when_types.kt
package com.zetcode

import javax.lang.model.type.ArrayType

fun main() {

    val variable: Any = 23

    when (variable) {

        is Int -> println("It is an integer")
        is String -> println("It is a string")
        is ArrayType -> println("It is an array")
    }
}

In the example, we check for a type of a variable in a when expression.

In this tutorial, we have covered when expression in Kotlin. You might also be interested in the related tutorials: Kotlin control flow tutorial, Kotlin ranges tutorial, or list all Kotlin tutorials.