3

我是一名涉足 Groovy 的 Java 程序员。您会在我的代码中注意到,我混合了一些特定于 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.
4

1 回答 1

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

}

switchIMO 干净一点。

于 2012-05-03T15:27:36.500 回答