When Expression

When Expression

The when is used like switch in our traditional languages. When can be used either an expression or statement.When matches its argument against all branches sequentially until some branch condition is satisfied. The else branch is evaluated if none of the other branch condition is satisfied.

fun main(args:Array<String>)
{

    var x=1    when (x) {
        1 -> print("x == 1")
        2 -> print("x == 2")
        else -> { // Note the block            print("x is neither 1 nor 2")
        }
    }
    
}

Output:
x == 1

If many conditions having same set of statements we can specify the branch conditions with comma.

fun main(args:Array<String>)
{

    var x=1    when (x) {
        0, 1 -> print("x == 0 or x == 1")
        else -> print("otherwise")
    }

}
output:
x == 0 or x == 1

In traditional switch case the condition must be a constant but by using when we can use arbitrary expressions as branch conditions.

fun main(args:Array<String>)
{
    var s="1"    var x=1;

    when (x) {
        parseInt(s) -> print("s encodes x")
        else -> print("s does not encode x")
    }
}
Output:
s encodes x

We can also check a condition with in a range or not with in a range.

fun main(args:Array<String>)
{
    var x=30    var validNumbers=20..30    when (x) {
        in 1..10 -> print("x is in the range")
        in validNumbers -> print("x is valid")
        !in 10..20 -> print("x is outside the range")
        else -> print("none of the above")
    }
}
Output:
x is valid



Comments