Please explain, why this isn't working (Groovy 2.0.5 on JDK7). I just want to add some map entries from a list.
def map = new HashMap<String,String>()
map << ["key":"value"]
def list = ["a","b","c"]
list.each {
map << [it:"value"]
}
println map
println map.a
println map.containsKey("a")
/*
[key:value, a:value, b:value, c:value]
null <- ?
false <- ?
*/
It is also not working with:
map << ["$it":"value"]
But it is working with:
map << [(""+it):"value"]
???
Best Answer
This
Just uses a key called
it
. If you wrap it in parentheses:It works as you wanted...
If you do:
Then, you can see that you have a
GStringImpl
: as a key rather than ajava.lang.String
(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:
As it just creates a String (by appending
it
to the empty String)Anyway...long story short, use
[(it):'value']