Check for several type inside when statement in Kotlin

88 views Asked by At

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
}
2

There are 2 answers

0
Giacomo Alzetta On BEST ANSWER

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.

1
gidds On

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.)