0

Let's say I've the following:

sealed class Color(val name: String) {
    object Red : Color("red")
    object Green : Color("green")
    object Blue : Color("blue")
    object Pink : Color("pink")
    object Yellow : Color("yellow")
}

Is it possible to check if a color is a primary one using a when statement i.e.:

when(color) {
    is Red, Green, Blue -> // primary color work
    is Pink -> // pink color work
    is Yellow -> // yellow color work
}
Benjamin
  • 7,055
  • 6
  • 40
  • 60

2 Answers2

4

Yes. According to the grammar of when


when
  : "when" ("(" expression ")")? "{"
        whenEntry*
    "}"
  ;
whenEntry
  : whenCondition{","} "->" controlStructureBody SEMI
  : "else" "->" controlStructureBody SEMI
  ;
whenCondition
  : expression
  : ("in" | "!in") expression
  : ("is" | "!is") type
  ;

the {","} means the element can be repeated more times separated by commas. Note however that you have to repeat is too and smartcasts wont work if you do with different unrelated types.

Giacomo Alzetta
  • 2,431
  • 6
  • 17
1

In addition to the other answers, you can do it slightly more concisely by omitting the is entirely:

when (color) {
    Red, Green, Blue -> // ...
    Pink -> // ...
    Yellow -> // ... 
}

This is checking the values for equality, unlike the is code which is checking the types. (Red, Green, &c are objects as well as types, which is why both work. I suspect that this way may be fractionally more efficient, too.)

gidds
  • 16,558
  • 2
  • 19
  • 26
  • It just occurred to me that what the OP wrote might even work... it will check for the type for `Red` and the value for `Green` and `Blue`. I assumed that the OP had already tried their suggested solution but they probably didn't (luckily, so now we all have a little bit clearer the possible choices). Thanks for the additional insights. – Giacomo Alzetta Dec 05 '18 at 13:00