Gradle/Groovy闭包范围混淆

Gradle/Groovy闭包范围混淆,groovy,gradle,Groovy,Gradle,我是Gradle/Groovy新手,在嵌套闭包中遇到了变量名解析的问题。我有一个自定义任务类,它定义了一些属性,我正在使用闭包实例化该类型的多个任务。这个闭包定义了一个名为与自定义任务类中的一个属性相同的变量,我遇到了一些奇怪的行为,这似乎与Groovy语言指南中的定义背道而驰。有人能回答下面代码中的问题吗 class Something extends DefaultTask { def thing = "a" } /* def thing = "b" // produces the

我是Gradle/Groovy新手,在嵌套闭包中遇到了变量名解析的问题。我有一个自定义任务类,它定义了一些属性,我正在使用闭包实例化该类型的多个任务。这个闭包定义了一个名为与自定义任务类中的一个属性相同的变量,我遇到了一些奇怪的行为,这似乎与Groovy语言指南中的定义背道而驰。有人能回答下面代码中的问题吗

class Something extends DefaultTask {
    def thing = "a"
}
/*
def thing = "b" // produces the error message:
                // > Could not find method b() for arguments [build_63hfhkn4xq8gcqdsf98mf9qak$_run_closure1@70805a56] on root project 'gradle-test'.
                // ...why?
*/
(1..1).each {
    def thing = "c"
    task ("someTask${it}", type: Something) {
        println resolveStrategy == Closure.DELEGATE_FIRST // prints "true"
        println delegate.class // prints "class Something_Decorated"
        println thing // prints "c" shouldn't this be "a" since it's using DELEGATE_FIRST?
        /*
        println owner.thing // produces the error message:
                            // > Could not find property 'thing' on root project 'gradle-test'
                            // shouldn't the "owner" of this closure be the enclosing closure?
                            // in that case shouldn't this resolve to "c"
        */
    }
}

编辑:
由于某种原因,在将所有
def
更改为
String
然后再返回到
def
之后,我无法再复制产生奇怪错误的
def thing=“b”
行,因为名为
thing
的变量是在闭包的词法范围内声明的,所以代码将打印
c
。这意味着闭包只能使用这个变量的值。什么会起作用:

  • 重命名闭包中定义的
    对象
    变量

  • 通过
    委托
    明确提及
    事物

    println delegate.thing


  • 因此,如果它不能首先在闭包的词法范围内找到名称,它将只使用委托策略(在第节中提到)?据我所知,是的。好的,这是有意义的。此外,我在
    def thing=“b”
    行上遇到的奇怪错误似乎在我将所有
    def
    更改为
    String
    ,然后返回到
    def
    (现在它只是处理一个错误,说
    thing
    已经在
    def thing=“c”定义了)
    行,这更有意义)。。。所以我要假设其中一个是某种奇怪的虫子或什么的。