这个问题与我观察到的代码行为有关。我给了3个案例。
def data = [:] // some map with data that has map values
def tag = "Some String from Config"
def results = []
// A) This worked
if(data."$tag") {
// need first key of the inner map
results << data."$tag".keySet().toArray()[0] ?: 0
} else {
results << 0
}
//B) Did not work
results << data."$tag" ? (data."$tag".keySet().toArray()[0] ?: 0) : 0 // Gave Null pointer exception
//C) Did not work
results << data."$tag" ?.keySet().toArray()[0] ?: 0 // Gave Null pointer exception
我不确定为什么,但我观察到这种行为。理想情况下,B和C语句也应该像A.一样。我在这里遗漏了什么?有什么问题?
Groovy版本:2.2.2 Java:7
答案 0 :(得分:4)
B 和 C 由于运算符的优先级而失败(. .?
(点)&gt; <<
&gt; {{1} };请参阅http://docs.codehaus.org/display/GROOVY/JN2535-Control 运营商重载 - 抱歉找不到更好的参考资料。)
?: