Groovy 脚本变量

对于 Groovy DSL 的用户,了解 Groovy 如何处理脚本变量非常重要。Groovy 有两种类型的脚本变量。一种具有局部范围,另一种具有脚本范围。

示例:变量范围:局部和脚本范围

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

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

配置和执行阶段

请务必记住,Gradle 有一个不同的配置和执行阶段(请参阅 构建生命周期)。

build.gradle.kts
val classesDir = file("build/classes")
classesDir.mkdirs()
tasks.register<Delete>("clean") {
    delete("build")
}
tasks.register("compile") {
    dependsOn("clean")
    val classesDir = classesDir
    doLast {
        if (!classesDir.isDirectory) {
            println("The class directory does not exist. I can not operate")
            // do something
        }
        // do something
    }
}
build.gradle
def classesDir = file('build/classes')
classesDir.mkdirs()
tasks.register('clean', Delete) {
    delete 'build'
}
tasks.register('compile') {
    dependsOn 'clean'
    def localClassesDir = classesDir
    doLast {
        if (!localClassesDir.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 任务在执行阶段删除该目录。