Groovy 2.1.0使用@CompileStatic的switch-case-break语句的奇怪行为 [英] Groovy 2.1.0 weird behaviour of switch-case-break statement with @CompileStatic

查看:157
本文介绍了Groovy 2.1.0使用@CompileStatic的switch-case-break语句的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手Groovy程序员,并且面临使用静态编译( @CompileStatic 注释)的switch-case-break语句的奇怪行为。看来 break s被忽略。

这是一个错误还是我在阅读文档时漏掉了一些东西。



环境:

   -  groovy sdk 2.1.0 
- Oracle JDK build 1.7.0_13 -b20 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
默认值:
println($ {val} default)
}
}
}

(new Test())。test()

输出:

 案例A 
案例B
默认
B案例B
B默认第二个测试:只是评论 @CompileStatic

code>



并且永久正常工作:

  A caseA 
B caseB
C default


解决方案

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

作为t之前的解决方法他被释放了,你可以用 break

 <$ c $ 'c'switch(val){
case'A':A:{
println($ {val} caseA)
break
}
case'B ':B:{
println($ {val} caseB)
break
}
默认值:
println($ {val} default)
}


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

解决方案

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")
        }

这篇关于Groovy 2.1.0使用@CompileStatic的switch-case-break语句的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆