考虑以下列表
def days = [ 'monday', 'tuesday']
和each
闭包与
days.each { it ->
println "it = $it (outer closure)" // prints day
def cloz = {
println "it = $it (subclosure)" // prints null, how to print day?
}
cloz()
}
来自it
子公开的 cloz
关闭无法访问。如何从subclosure引用外部封闭参数?
答案 0 :(得分:3)
您可以通过多种方式获得所需的行为。问题是内部闭包中的隐式it
变量是从外部闭包中踩到显式it
参数。
你可以这样做:
def days = [ 'monday', 'tuesday']
days.each { outer ->
println "it = $outer (outer closure)" // prints day
def cloz = { inner ->
println "it = $outer (subclosure)" // prints day
}
cloz()
}
或者这个:
def days = [ 'monday', 'tuesday']
days.each { day ->
println "it = $day (outer closure)" // prints day
def cloz = {
println "it = $day (subclosure)" // prints day
}
cloz()
}
等等...
我希望有所帮助。