如何在Groovy中从subclosure引用外部闭包参数

时间:2015-08-09 23:36:27

标签: groovy

考虑以下列表

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引用外部封闭参数?

1 个答案:

答案 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()
}

等等...

我希望有所帮助。