我是一名 Java 程序员,正在涉足 Groovy。您会注意到,在我的代码中,我混合了一些 Java 特定的语法,这对于 Groovy 来说应该是没问题的。
谁能向我解释为什么 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.
最佳答案
我知道这并不能回答你为什么你的代码不适合你的问题,但是如果你想要一个稍微更时髦/更好的方法来实现你的代码,你可以将你的值放入映射中,这样你就不会必须使用 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"
}
}
在我看来,比开关
干净一点。
关于string - 在 Groovy Switch-Case 语句中使用静态字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10433997/