kotlintypecheckingkotlin-when

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
}

Solution

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