Groovy script variables

对于Groovy DSL的用户,了解Groovy如何处理脚本变量很重要. Groovy有两种类型的脚本变量. 一个具有本地范围,一个具有脚本范围.

Example: Variables scope: local and script wide

scope.groovy
String localScope1 = 'localScope1'
def localScope2 = 'localScope2'
scriptScope = 'scriptScope'

println localScope1
println localScope2
println scriptScope

closure = {
    println localScope1
    println localScope2
    println scriptScope
}

def method() {
    try {
        localScope1
    } catch (MissingPropertyException e) {
        println 'localScope1NotAvailable'
    }
    try {
        localScope2
    } catch(MissingPropertyException e) {
        println 'localScope2NotAvailable'
    }
    println scriptScope
}

closure.call()
method()
groovy scope.groovy输出
> groovy scope.groovy
localScope1
localScope2
scriptScope
localScope1
localScope2
scriptScope
localScope1NotAvailable
localScope2NotAvailable
scriptScope

用类型修饰符声明的变量在闭包中可见,但在方法中不可见.

Configuration and execution phase

重要的是要记住Gradle具有不同的配置和执行阶段(请参阅Build Lifecycle ).

例子1.不同的配置和执行阶段
build.gradle
def classesDir = file('build/classes')
classesDir.mkdirs()
task clean(type: Delete) {
    delete 'build'
}
task compile {
    dependsOn 'clean'
    doLast {
        if (!classesDir.isDirectory()) {
            println 'The class directory does not exist. I can not operate'
            // do something
        }
        // do something
    }
}
build.gradle.kts
val classesDir = file("build/classes")
classesDir.mkdirs()
tasks.register<Delete>("clean") {
    delete("build")
}
tasks.register("compile") {
    dependsOn("clean")
    doLast {
        if (!classesDir.isDirectory) {
            println("The class directory does not exist. I can not operate")
            // do something
        }
        // do something
    }
}
gradle -q compile输出
> gradle -q compile
The class directory does not exist. I can not operate

由于目录的创建是在配置阶段进行的,因此clean任务会在执行阶段删除目录.