`when(x)` behaviour when x is used in test

#1

Hi all,

I hit into case where when was used as in given code by accident

val a: Any? = null;
                when(a){
                    a is String  -> TODO();
                    isNull(a) -> TODO();
                }

It is translated as (a == a is String) -> and (a == isNull(a)), which is probably good but not very intuitive. Maybe it would be nice to have it reported as warning by compiler. Or be compiled by more intuitive way;). I have looked into reference and such mixed case is not mentioned there.

3 Likes
#2

You mixing 2 variations of when. You should write (also hold back on semi-colon (“;”)).

val a: Any? = null
when(a){
is String -> TODO()
null -> TODO()
else -> TODO()
}

I didn’t check what it will be compiled into, but I am sure it will be what you expect :wink:

#3

No sir. Your when statement can drop the (a) at the beginning and it would work the exact same. And a when with no variable is basically a long if else if chain where

When you use a when statement, if you are checking a type you can drop the variable name in the check

when (a) {
    is String -> TODO()
}

When checking equality, you can drop the equals and just put what you are comparing it to in the when statement. You dont use is with null because null is not a type!

when (a) {
    null -> TODO()
}