Thursday, June 14, 2012

Groovy issues / things to learn - Keys of a map containing variable values

We are into developing groovy scripts these days and I have pondered about how to make the key a variable and today, I have come across a use case and a way to do this.

If you have a Map of [name : value], the name here itself is a literal, but if you would like the name to be a variable, you would have to enclose it within a paranthesis. For instance, this map would become [(name) : value]. Let us day, if we have defined name as

def name = "test", the output of the map will be {"test" : value}, instead of {name: value}. Here since the name is enclosed within a paranthesis, essentially it acts like a bind variable and replaces the derived value of "name", which turns out to be "test" in this case.