Benjamin
Benjamin

Reputation: 7368

Check for several type inside when statement in Kotlin

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
}

Upvotes: 0

Views: 178

Answers (2)

gidds
gidds

Reputation: 18567

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

Upvotes: 1

Giacomo Alzetta
Giacomo Alzetta

Reputation: 2479

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.

Upvotes: 4

Related Questions