簡體   English   中英

Gradle/Groovy 閉包范圍混淆

[英]Gradle/Groovy closure scope confusion

我是 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"行產生那個奇怪的錯誤

代碼打印c是因為名為thing的變量是在閉包的詞法范圍內聲明的。 這意味着閉包只能使用這個變量的值。 什么會起作用:

  1. 重命名閉包中定義的thing變量。

  2. 通過delegate明確指代thing

    println delegate.thing

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM