Gradle variable scoping

1.9k views Asked by At

I my root project I defined a variable and a method using it like

// An immediately executed closure (I hope)
def myvar = ({-> do something})()

def myfun() {
    println myvar + ":" + project
}

and called it in a subproject. This lead to an error like

Could not find property 'myvar' on root project 'root'.

I find it strange as myvar is in scope on the function definition (so I'm probably doing something different?). Ii looks like dynamic scoping, but I can't believe it.

I know about project.ext, but I don't want to make myvar available elsewhere.

So I moved the definition into the declaration (it gets evaluated multiple times now, but who cares), but then I found out that project refers to the root project, rather than the subproject calling the function (lexical scoping). Can I get the current project without passing it explicitly?

1

There are 1 answers

0
Peter Niederwieser On BEST ANSWER

Local variables declared at the outermost level of a script aren't in scope of methods in the same script. This is due to how Groovy translates a script into a runnable class. One way around this is to use ext.myfun = { ... } instead, which solves the scoping problem and doesn't affect call sites (which can still use myfun()).

Your other problem seems unrelated. project refers to the project that the script is associated with, and isn't determined based on the caller. It isn't possible to get the caller's project without passing it. However, it's possible to declare ext.myfun for every project, e.g. in the root script's allprojects {} block.