Scope of variables in groovy scripts

Hi all,

I wanted to try groovy in the script editor in Fiji since some people recommend the features of the language. I like how easy I can convert my Java code into groovy, but I came across an issue with the scope of the variables.


aMethod()

def aMethod() {
	str = "ham"
	bMethod()
	println(str)
}

def bMethod() {
	str = "eggs"
}

Output:

Started test.groovy at Sat Aug 03 01:14:11 CEST 2019
eggs

I would expect this to print ham. Am I missing something? I have zero experience in groovy. How is str some kind of global variable? If this is how it’s supposed to work, I can not recommend this as the choice of script language to others.

@fjug @ctrueden

5 Likes

@frauzufall,

Nice find, I learned something from your post!

From this:
https://code-maven.com/groovy-variable-scope

Id guess that prefixing your str variables with def would give the behavior you expect. (Not near a PC atm).

John

6 Likes

Yep, I end up working around this all of the time, though I am generally from the opposite direction. I have to remove my defs when combining groups of scripts so they don’t throw errors! Which probably really means I need to plan out my scripts better with the expectation that I’ll be merging them.

2 Likes

Yes, that’s it! Thank you :slight_smile:

2 Likes