Home > other >  gradle access global variable from function call not work
gradle access global variable from function call not work

Time:05-01

I am trying to access a global variable from a function as below:

def var = "hello"

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

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

gradle report error message:

> 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.

What's the proper way to access a global variable from a function call?

CodePudding user response:

def are not visible to functions, you have pass the value to the function. use ext. properties if you need it that way

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

  • Related