4

I'm novice groovy programmer, and I faced weird behaviour of switch-case-break statement with static compilation (@CompileStaticannotation). It seems that breaks are ignored.
Is it a bug or I've missed something while reading documentation.

Environment:

    - groovy sdk 2.1.0
    - Oracle JDK build 1.7.0_13-b20 on Mac OS X Lion 10.7.5

Test case:

import groovy.transform.CompileStatic
@CompileStatic
class Test {
    def test() {
        ['A', 'B', 'C'].each { String val ->
            switch (val) {
                case 'A' :
                    println("${val} caseA")
                    break
                case 'B' :
                    println("${val} caseB")
                    break
                default : 
                    println("${val} default")
            }
        }
    }
}
(new Test()).test()

Output:

A caseA
A caseB
A default
B caseB
B default
C default

Second test: just comment @CompileStatic

And everithing works fine:

A caseA
B caseB
C default
  • 1
    Looks like a bug to me, can you report it on [the Groovy JIRA](http://jira.codehaus.org/browse/GROOVY)? – tim_yates Feb 08 '13 at 14:30
  • Yes, I've just reported it [GROOVY-5984](http://jira.codehaus.org/browse/GROOVY-5984) – Igor Kovalchuk Feb 08 '13 at 15:04
  • 1
    Cool :-) ([looks like it was fixed yesterday](https://github.com/groovy/groovy-core/commit/89d3c59e5dd377989121ffaddc293c0915ebf69c)) I posted a vaguely unpleasant workaround below to get this working with 2.1.0 :-) – tim_yates Feb 08 '13 at 15:13

1 Answers1

2

This seems to be a bug in Groovy 2.1.0 (thanks for posting it to the JIRA, it looks like it will be fixed in Groovy 2.1.1)

As a workaround until this is released, you can use labeled blocks for your case statements with break

        switch (val) {
            case 'A' : A:{
                println("${val} caseA")
                break
            }
            case 'B' : B:{
                println("${val} caseB")
                break
            }
            default : 
                println("${val} default")
        }
tim_yates
  • 167,322
  • 27
  • 342
  • 338