闭包中的代码可以引用it
变量。
8.times { println it }
或
def mywith(Closure closure) {
closure()
}
mywith { println it }
考虑到这种行为,您不能期望下面的代码打印0011
2.times {
println it
mywith {
println it
}
}
相反,我不得不写
2.times { i ->
println i
mywith {
println i
}
}
我的问题是:没有参数的闭包为什么要覆盖it
变量,即使它们不需要它。
发布于 2010-03-02 17:14:44
我认为这与Groovy的formal Closure definition有关:
闭包可以有1...N个参数,这些参数可以是静态类型的,也可以是无类型的。如果没有显式参数命名,则可以通过名为it的隐式非类型化参数使用第一个参数。如果调用方未指定任何参数,则第一个参数(通过扩展,它)将为null。
这意味着Groovy闭包将始终至少有一个称为它的参数(如果没有另外指定),如果不作为参数给出,它将为null。
第二个示例使用封闭闭包的作用域。
发布于 2010-03-03 00:05:39
如果你像这样定义一个闭包
def closure = {println "i am a closure"}
它看起来没有参数,但实际上它有一个名为it
的隐式参数。这是通过以下方式确认的:
def closure = {println "i am a closure with arg $it"}
closure("foo")
哪种打印
"i am a closure with arg foo“
如果您确实想定义一个带0个参数的闭包,请使用以下代码:
def closure = {-> println "i am a closure"}
因此,您的示例可以重写为:
2.times {
println it
mywith {->
println it
}
}
https://stackoverflow.com/questions/2361650
复制相似问题