Sachin Verma
Sachin Verma

Reputation: 3802

Map Keys are Objects or not in Groovy?

I am a Java Developer and learning groovy nowadays but groovy is messing with my brain , there are things I need help with and major of them is listed here:

def map = [inm1:'hello',int2f:'world']
map.keySet().each{
println it.class.name
println "values of Key"+it.charAt(2)
}

In above code inm1 and int2f are normal variables in Java but in groovy they are String Values not just the variables with String values, they actually are String Objects itself.
However it they are Strings then why no single or double " or ' quotes. I couldn't understand this concept and I just want your help badly.
Also provide me some resources to learn groovy , I did find many resources but they take things like above mentioned too lightly.

Upvotes: 5

Views: 4813

Answers (1)

tim_yates
tim_yates

Reputation: 171084

Simple keys are automatically converted to Strings in Groovy as it simplifys regular Map creation.

If you want to evaluate keys from variables, then you need to put them in brackets, ie:

Integer inm1 = 10
String  int2f = 'hello'

// Regular map with string keys
assert [ inm1:'hello', int2f:'world' ] == [ 'inm1':'hello', 'int2f':'world' ]

// And evaluated keys in parentheses
assert [ (inm1):'hello', (int2f):'world' ] == [ 10:'hello', 'hello':'world' ]

Upvotes: 15

Related Questions