gradle 从函数调用访问全局变量不起作用

gradle access global variable from function call not work

我正在尝试从以下函数访问全局变量:

def var = "hello"

def func() {
    println("func:" + var)
}

tasks.register('callme') {
    doLast {
        print("callme:" + var)
        func()
    }
}

gradle 报错信息:

> Task :callme FAILED
callme:hello
FAILURE: Build failed with an exception.

* Where:
Build file '/vagrant/work/gradle/build.gradle' line: 67

* What went wrong:
Execution failed for task ':callme'.
> Could not get unknown property 'var' for root project 'demo' of type org.gradle.api.Project.

从函数调用访问全局变量的正确方法是什么?

def 对函数不可见,您已将值传递给函数。 使用分机。属性,如果你需要的话

ext.extVar = "ext-hello"
def strVar = "hello"
def func(String strVar) {
    println("func - def:" + strVar)
    println("func - ext:" + extVar)
}
println "from root "
func(strVar)
tasks.register('callme') {
    doLast {
        println("callme:" + strVar)
        func(strVar)
    }
}
--


from root 
func - def:hello
func - ext:ext-hello

> Task :callme
callme:hello
func - def:hello
func - ext:ext-hello