I would like help understanding how Groovy manages scope and variables when passed between functions. Say I declare def foo
in my main method and pass it as an argument to a private void method, changeStuff. Then I can make changes like follows:
public static void main(args) {
def foo = [:];
changeStuff(foo);
println(foo);
}
private static void changeStuff(foo) {
foo.bar = "new stuff";
}
The result printed is [bar:new stuff]
But I have a hard time manipulating foo in other ways. See these next two examples:
public static void main(args) {
def foo = [:];
changeStuff(foo);
println(foo);
}
private static void changeStuff(foo) {
def newStuff = [:]
newStuff.extra = "extra stuff";
foo = newStuff;
}
prints: [:]
public static void main(args) {
def foo = "before";
changeStuff(foo);
println(foo);
}
private static void changeStuff(foo) {
foo = "after";
}
prints before
I know there is some concept here that I am not fully understanding, maybe related to def
? Any summary or direction on where I can learn more about this is appreciated.