Kotlin when Expression: In this tutorial, you will learn about when construct in Kotlin with the assistance of different examples.

Kotlin, when the expression is a conditional expression that returns the worth. Kotlin, when the expression is the substitution of the switch statement. Kotlin, when expression functions as a switch statement of other languages (Java, C++, C).

Kotlin when Construct

The when construct in Kotlin can be considered as a substitution for Java switch Statement. It assesses a segment of code among numerous other options.


Example: Simple when Expression

fun main(args: Array<String>) {

    val a = 12
    val b = 5

    println("Enter operator either +, -, * or /")
    val operator = readLine()

    val result = when (operator) {
        "+" -> a + b
        "-" -> a - b
        "*" -> a * b
        "/" -> a / b
        else -> "$operator operator is invalid operator."
    }

    println("result = $result")
}

At the point when you run the program, the output will be a like thing:

Enter operator either +, -, * or /
*
result = 60

The program above takes an input string from the user (Recommended Reading: Get String Input from the User in Kotlin). Assume, the user entered *. For this situation, the expression a * b is assessed, and the worth is assigned to the variable outcome.

In the event that none of the branch conditions are satisfied (user entered anything aside from +, – , *, or/) , else branch is assessed.


In the above example, we used when as an expression. Notwithstanding, it’s not required to use when as an expression. For instance,

fun main(args: Array<String>) {

    val a = 12
    val b = 5

    println("Enter operator either +, -, * or /")
    val operator = readLine()

    when (operator) {
        "+" -> println("$a + $b = ${a + b}")
        "-" -> println("$a - $b = ${a - b}")
        "*" -> println("$a * $b = ${a * b}")
        "/" -> println("$a / $b = ${a / b}")
        else -> println("$operator is invalid")
    }
}

At the point when you run the program, the output will be a like thing:

Enter operator either +, -, * or /
-
12 - 5 = 7

Here, when isn’t an expression (return value from when isn’t assigned to anything). For this situation, the else branch isn’t compulsory.


Few possibilities

Consolidate at least two branch conditions with a comma. For instance,

fun main(args: Array<String>) {

    val n = -1

    when (n) {
        1, 2, 3 -> println("n is a positive integer less than 4.")
        0 -> println("n is zero")
        -1, -2 -> println("n is a negative integer greater than 3.")
    }
}

At the point when you run the program, the output will be:

n is a negative integer greater than 3.

Check value in the range. For instance,

fun main(args: Array<String>) {

    val a = 100

    when (a) {
        in 1..10 -> println("A positive number less than 11.")
        in 10..100 -> println("A positive number between 10 and 100 (inclusive)")
    }
}

At the point when you run the program, the output will be:

A positive number between 10 and 100 (inclusive)

Check if a value is of a specific type.

To check whether a worth is of a specific sort in runtime, we can use is and !is operator. For instance,

when (x) {
    is Int -> print(x + 1)
    is String -> print(x.length + 1)
    is IntArray -> print(x.sum())
}

Use expressions as branch condition. For example,

fun main(args: Array<String>) {

    val a = 11
    val n = "11"

    when (n) {
        "cat" -> println("Cat? Really?")
        12.toString() -> println("Close but not close enough.")
        a.toString() -> println("Hello! It's eleven.")
    }
}

At the point when you run the program, the output will be:

Hello! It's eleven.

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.


0 Comments

Leave a Reply

Avatar placeholder