在Groovy Switch-Case语句中使用静态字符串

时间:2012-05-03 14:57:56

标签: string groovy switch-statement case

我是一名Java程序员,正在涉足Groovy。您将在我的代码中注意到我混合了一些特定于Java的语法,这可能是Groovy的A-Okay。

有人可以向我解释为什么Groovy不会接受静态变量作为CASE参数吗?或者如果它会,你能看到我在这里做错了吗?

public static final String HIGH_STRING = "high";
public static final String LOW_STRING  = "low";

... //other code, method signature, etc.

def val = "high";
switch (val) {

   case HIGH_STRING:
     println("string was high"); //this won't match
     break;

   case LOW_STRING:
     println("string was low");  //this won't match
     break;

   //case "high":
   //  println("string was high"); //this will match because "high" is a literal
   //  break;

   default:
     println("no match");
}

... //other code, method closeout, etc.

1 个答案:

答案 0 :(得分:4)

我知道这并没有回答你为什么你的代码不能为你工作的问题,但是如果你想要一个稍微更好/更好的方法来实现你的代码,你可以将你的值扔到地图中,这样你就不会必须使用switch声明:

class ValueTests {
    public static final String HIGH_STRING = "high"
    public static final String LOW_STRING  = "low"

    @Test
    void stuff() {
        assert "string was high" == getValue("high")
        assert "string was low" == getValue("low")
        assert "no match" == getValue("higher")
    }

    def getValue(String key) {
        def valuesMap = [
            (HIGH_STRING): "string was high", 
            (LOW_STRING):"string was low"
        ]
        valuesMap.get(key) ?: "no match"
    }

}

switch IMO更清洁。