Breako Breako
Breako Breako

Reputation: 6461

Using Longs as Keys in Groovy Map

I want a Map to contain numeric mappings, I do:

Long long1 = 44l;
Long long2 = 45l;

def myMap = [long1: 26, long2: 27];

println(myMap)

But what is outputted is:

[long1:26, long2:27]

I want it to be:

[44: 26, 45: 27]

And I need to do this through variables, as I don't know what the values will be until runtime?

Thanks.

Upvotes: 1

Views: 594

Answers (1)

grantmcconnaughey
grantmcconnaughey

Reputation: 10699

Change your map declaration to the following:

def myMap = [(long1): 26, (long2): 27]

Groovy is doing some implicit variable-name-to-String conversion when you declare your Map, so instead of it evaluating long1 it is using long1 as a String key name. Also see this StackOverflow question.

Upvotes: 7

Related Questions