我试图理解为什么在下面的代码片段中,如果 GString 在闭包内创建,它的评估很好,但如果我尝试在外部创建 String 并尝试在闭包内对其进行评估,则会引发异常:
map1 = ['foo': 1, 'bar': 2]
map2 = ['foo': 3, 'bar': 4]
dynamicallyGeneratedString = "key1: ${->key1}, val1: ${->value1}, key2: ${->key2}, val2: ${->value2}"
map1.each { key1, value1 ->
map2.each { key2, value2 ->
println "key1: ${->key1}, val1: ${->value1}, key2: ${->key2}, val2: ${->value2}" // works as expected
// println dynamicallyGeneratedString // throws MissingPropertyException
}
}
在这两种情况下,所需的输出都是:
key1: foo, val1: 1, key2: foo, val2: 3
key1: foo, val1: 1, key2: bar, val2: 4
key1: bar, val1: 2, key2: foo, val2: 3
key1: bar, val1: 2, key2: bar, val2: 4
我的目标是根据其他一些条件动态生成一个字符串,然后在遍历地图时懒惰地评估它的内容。
这是一种有效的方法吗?