📜  kotlin when range (1)

📅  最后修改于: 2023-12-03 14:43:41.164000             🧑  作者: Mango

Kotlin When Range

Kotlin when expression is similar to switch-case statements in other programming languages. However, Kotlin's when expression is more powerful and flexible. With Kotlin when expression, you can use ranges as input and specify a range of values to match against.

Syntax

The basic syntax of Kotlin when expression with range is as follows:

when (variable) {
    in lowerValue..upperValue -> {
        //logic
    }
    else -> {
        //logic
    }
}

In the above syntax, variable is the input variable that you want to match against. lowerValue and upperValue specify the lower and upper bounds of the range. You can also use !in keyword to match the input variable outside the range.

Example

Let's see an example of using when expression with range in Kotlin.

fun main() {
    val value = 9
    when (value) {
        in 1..3 -> println("Value is between 1 and 3")
        in 4..6 -> println("Value is between 4 and 6")
        in 7..9 -> println("Value is between 7 and 9")
        else -> println("Value is not between 1 and 9")
    }
}

In the above example, we have specified three different ranges to match against the input variable value. If value is not within any of these ranges, then the final else statement will be executed.

Conclusion

Kotlin when expression with range is a powerful feature that makes it easy to match a range of values against an input variable. This feature is particularly useful when you want to execute different logic based on the range of values that the input variable falls within.