简体   繁体   中英

Gradle/Groovy closure scope confusion

I'm new to Gradle/Groovy and am running into issues with variable name resolution in nested closures. I have a custom task class that defines some properties and I am instantiating potentially multiple tasks of that type using a closure. This closure defines a variable named the same as one of the properties in the custom task class and I am running into some odd behavior which seems to go against what is defined in the Groovy language guide. Could someone please answer the questions in the code below?

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"
        */
    }
}


EDIT: For some reason after changing all of the def into String and then back into def I can no longer replicate the def thing = "b" line producing that weird error

The code prints c because the variable named thing is declared within the lexical scope of the closure. It means that closure can just use the value of this variable. What will work:

  1. Renaming the thing variable defined in the closure.

  2. Explicitly referring to thing via delegate :

    println delegate.thing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM