Search code examples
groovyswitch-statement

Groovy behavior of switch statement


I haven't used enums in Groovy much yet, but the following code doesn't behave as I would expect:

enum Enum{ A, B }

def e = Enum.A

switch(e) {
    case Enum.A:
        println("A: ${Enum.A.isCase(e)}")
    case Enum.B:
        println("B: ${Enum.B.isCase(e)}")
}

This prints

A: true
B: false

Am I misusing enum or why is the Enum.B case being executed in the switch statement?

EDIT

Thanks for the answers! I edited the question, because it has nothing to do with enums. It was just my lack of understanding the switch-statement. The behavior is consistent with Java switch and I wasn't aware that also non-matching cases were executed:

All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered

I guess I have to check some code at work...


Solution

  • If you are using Groovy 4.0+ you can use switch expressions instead of switch statements. They can return a value and behave a little bit more like people expect the switch statement to behave (for example there is no need for breaks as there is no fallthrough)

    println switch(e) {
        case Enum.A -> "A: ${Enum.A.isCase(e)}"
        case Enum.B -> "B: ${Enum.B.isCase(e)}"
    }