Variables are required to be declared in Class while not required in Script
1 | groovy:000> class Callee { |
Note the line “27” doesn’t declare(while the line “3” and line “15” do) the variable “name” so error happens.
“Scripts and Classes“ has more details.
From my perspective, this is unintuitive and introduces confusion. It also means “script” and “class” in Groovy are executed in different ways under the hood. Most likely it is a trade-off to keep the compatibility with Java.
The method how to add a varible value as the key of a Map entry
This error took me a couple of hours to find the root cause of an error in my code. The trick part is that: when you print the Map in log, you don’t know the type of the entry key, what you see is just the String value… :(
The following answer is from here.
This:
1 | map << [it:"value"] |
Just uses a key called it. If you wrap it in parentheses:
1 | map << [(it):"value"] |
It works as you wanted…
If you do:
1 | map << ["$it":"value"] |
Then, you can see that you have a GStringImpl: as a key rather than a java.lang.String:
1 | println map.keySet()*.getClass().name |
(package names omitted for brevity)
Then, you try and look up a GString key with a String, and this fails (see the ‘GStrings aren’t Strings’ section on this page)
This works:
1 | map << [(""+it):"value"] |
As it just creates a String (by appending it to the empty String)
Anyway…long story short, use [(it):’value’]