【问题标题】:Groovy 2.1.0 weird behaviour of switch-case-break statement with @CompileStaticGroovy 2.1.0 带有@CompileStatic 的 switch-case-break 语句的奇怪行为
【发布时间】:2013-02-08 14:27:03
【问题描述】:

我是新手 groovy 程序员,我遇到了使用静态编译 (@CompileStaticannotation) 的 switch-case-break 语句的奇怪行为。 breaks 似乎被忽略了。
是错误还是我在阅读文档时遗漏了什么。

环境:

    - 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

【问题讨论】:

标签: groovy switch-statement compile-static


【解决方案1】:

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

在此版本发布之前,作为一种解决方法,您可以在 breakbreak 的案例语句中使用带标签的块

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多