YQadoome
YQadoome

Reputation: 178

Wrong syntax of condition in when using kotlin

this is a syntax error

 in "C","c".."Z","z"->{//erorr:ClosedRange
        print("Last")
    }

but this works ,why ?

in "C".."Z","z"->{
        print("Last")
    }

Upvotes: 2

Views: 190

Answers (3)

user8959091
user8959091

Reputation:

Just to make things more complicated (this is not an answer of course), if you run the following code:

val c = "California"

when (c) {
    in "A".."z"-> {
        print("Yes")
    }
    else -> {
        print("No")
    }
}

what do you think will be printed? Yes because "A"<"California"<"z"

So be very careful with string ranges.

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170723

This just makes zsmb13's answer more explicit, but doesn't fit well into a comment.

In your first version the compiler sees 3 conditions: in "C", "c".."Z", and "z". The first is valid e.g. for String, because it calls the String.contains(String) method. The second checks whether the argument of when is equal to the range "c".."Z", and the third whether it's equal to the string "z".

So if the compiler can tell the argument isn't a ClosedRange (because a String can't be a ClosedRange), then it can't be equal to "c".."Z" and the condition can't succeed.

Upvotes: 0

zsmb13
zsmb13

Reputation: 89548

The second version works because you can list multiple conditions that will all run the same branch of code. in "C".."Z" is a condition for the value being in a range, while "z" is a condition for the value being exactly "z".

You can also do what you were looking for, if you list the two range conditions separately:

when(x) {
    in "C".."Z", in "c".."z" -> {
        /* Runs when value is in either range */
    }
    2, 4, 9 -> { 
        /* Another example of multiple conditions for the same 
           branch (only one has to match, of course) */
    } 
} 

Upvotes: 1

Related Questions