134

Let's say I have

def A = "abc"
def X = "xyz"

how do I create a Map where, instead of

def map = [A:1, X:2]

I get instead the equivalent of writing

def map = [abc:1, xyz:2]

but can use a variables A and X for the key?

P.S.: Same question for the value part of the map.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Ray
  • 5,885
  • 16
  • 61
  • 97

2 Answers2

216

Use this:

def map = [(A):1, (X):2]

For the value-part it's even easier, since there is no automagic "convert text to string" happening:

def map = [keyA:A, keyX:X]
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 19
    Just to provide a reference: the [Map Documentation](http://groovy.codehaus.org/JN1035-Maps) says: `To use the value of a String as the key value of a map, simply surround the variable with parenthesis.` – mmigdol Oct 13 '11 at 15:43
  • 4
    @mmigdol this quote is from [old groovy documentation](http://groovy.jmiguel.eu/groovy.codehaus.org/JN1035-Maps.html) in the [newest documentation](http://groovy-lang.org/groovy-dev-kit.html#Collections-Maps) its like this: `Map keys are strings by default: [a:1] is equivalent to ['a':1]. This can be confusing if you define a variable named a and that you want the value of to be the key in your map. If this is the case, then you must escape >the key by adding parenthesis..` – Michal Bernhard Mar 02 '16 at 13:10
  • So what is the diff between def map = [(A):1, (X):2] . and def map = ["$A":1, (X):2] if any? – TriMix Apr 06 '18 at 21:05
  • 3
    @TriMix the difference is Strings vs GStrings. With `[(A):1, (X):2]`, the variable is being escaped into a String. With `["$A":1, (X):2]`, the `"$A"` is an interpolated string which results in a GString. Maps expect the keys to be immutable which a GString doesn't provide. – Josh Lyon Apr 18 '18 at 16:19
28

Further to Joachim's answer, if you want to add entries to an existing map and the keys are variables, use:

def map = [:]
def A = 'abc'
map[A] = 2

If you use:

map.A = 2

It is assumed that you want to use the literal string 'A' as the key (even though there is a variable named A in scope.

Update

As @tim_yates pointed out in a comment, a key variable will also be resolved if you use:

map."$A" = 2

though personally I prefer to use the [A] syntax because refactoring tools might miss the "$A" reference if the variable is renamed

Community
  • 1
  • 1
Dónal
  • 185,044
  • 174
  • 569
  • 824