All variables seem to be global in my groovy scripts I run on groovy script engine. I made some groovy class but when I make variables, they can be accessed from everywhere. for exaple.
class test{
void func1{ a=4 }
void func2{ print(a) }
}
When I invoke this class function func1 from scala then invoke func2, it results “4”. Weird thing is if I declare variables like “def a=0” in the function, the scope of the variable will be limited with in the function.
I’m loading my groovy scripts from GroovyScriptEngine like this(using scala)
var gse = new GroovyScriptEngine(pathList.toArray)
var scriptClass = gse.loadScriptByName(file.getName())
var i = scriptClass.newInstance().asInstanceOf[GroovyObject]
then using invokeMethod to invoke functions in the groove script class. Is there anyway to make variable scopes limited with in functions by default?
That’s the expected behaviour, described in Scoping and the Semantics of “def”.
Using an undeclared variable in a Groovy script creates a binding variable. Binding variables are global to your script. If you declare your variable with
def, it become function local.This behavior only applies because you load your code as a script. I don’t believe its possible to change it. Just use a declaration (
defor a type) when you need a local variable.Note that you can also define a binding variable (global) by using the @Field annotation:
is equivalent to