Groovy 2.1.0带有@CompileStatic的switch-case-break语句的奇怪行为

时间:2013-02-08 14:27:04

标签: groovy switch-statement compile-static

我是新手groovy程序员,我遇到了使用静态编译(@CompileStatic注释)的switch-case-break语句的奇怪行为。看来break被忽略了 这是一个错误还是我在阅读文档时遗漏了一些东西。

环境:

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

测试用例:

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

输出:

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

第二次测试:只评论@CompileStatic

并且永远工作得很好:

A caseA
B caseB
C default

1 个答案:

答案 0 :(得分:2)

这似乎是Groovy 2.1.0中的一个错误(感谢将其发布到JIRA,看起来它将在Groovy 2.1.1中修复)

作为一种解决方法,在此版本发布之前,您可以使用带有break的案例陈述的带标签的块

        switch (val) {
            case 'A' : A:{
                println("${val} caseA")
                break
            }
            case 'B' : B:{
                println("${val} caseB")
                break
            }
            default : 
                println("${val} default")
        }