Groovy 脚本变量

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

示例:变量范围:本地和脚本范围

范围.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任务会在执行阶段删除该目录。