Reduced implementation of conditions in "if" and "when" expressions

Is there an implementation of this type (or similar)?

when {
firstVal == 1 || 2 -> some code
secondVal == “a” && “b” -> some code
}

Otherwise, I would not want to write:

if (firstVal == 1 || firstVal == 2) {
some code
}

If this is not, is it possible to add it to the language?

You can consider

when (firstVal) {
    1, 2 -> TODO()
    else -> when (secondVal) {
        "a", "b" -> TODO()
    }
}

if (firstVal in 1..2) {
    TODO()
}

if (firstVal in intArrayOf(1, 2)) {
    TODO()
}

Or just:

when {
    firstVal in 1..2 -> TODO()
    secondVal == "a" && 
        secondVal.someOtherProp =="b" -> TODO()
}

If you don’t specify a variable on a when it just becomes a sequentially evaluated set of rules where the first satisfied condition matches and terminates the evaluation. Basically equivalent to an if(...) {...} else if (...) {...} else if (...) {...} else {...} chain.

1 Like