[英]Strange behavior of groovy closures referencing class field
Here's a code sample: 这是一个代码示例:
class StaticTest {
static def list = [1, 2, 3]
void printsNothing() {
[].with { list.each { println it } }
}
void printsList() {
new Object().with { list.each { println it } }
}
public static void main(String[] args) {
new StaticTest().with {
println "Expected: "
printsList()
println "Strange: "
printsNothing()
}
}
}
As you can see, closures in printsNothing
and printsList
are identical, nevertheless the result differs as printsNothing
indeed prints nothing as if the list
was empty. 如您所见,
printsNothing
和printsList
中的闭包是相同的,但是结果有所不同,因为printsNothing
实际上不会打印任何内容,就好像list
为空。 Here's the output: 这是输出:
Expected:
1
2
3
Strange:
I'm using Groovy 2.2.2 with invokedynamic support enabled. 我使用启用了invokedynamic支持的Groovy 2.2.2。
Any suggestions on whether this is a bug or I just know nothing about Groovy? 关于这是一个错误还是我对Groovy一无所知,有什么建议吗?
This was on the user mailing list recently , it's because it's looking for the property list
in all of the elements of the empty list (and [].list == []
). 这是最近在用户邮件列表上的,这是因为它正在空列表的所有元素(和
[].list == []
)中寻找属性list
。 If you change the printsNothing
method to: 如果将
printsNothing
方法更改为:
void printsNothing() {
// Use this.list to get round local `with` scoping
[].with { this.list.each { println it } }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.