Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Keys are Objects or not in Groovy?

Tags:

java

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.

like image 966
Sachin Verma Avatar asked Aug 19 '13 09:08

Sachin Verma


1 Answers

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' ]
like image 114
tim_yates Avatar answered Sep 28 '22 06:09

tim_yates