Issue Details (XML | Word | Printable)

Key: GROOVY-1288
Type: Bug Bug
Status: Closed Closed
Resolution: Won't Fix
Priority: Major Major
Assignee: Guillaume Laforge
Reporter: Markus Halttunen
Votes: 0
Watchers: 0
Operations

If you were logged in you would be able to see more operations.
groovy

When creating a map, the key cannot reference to a variable?

Created: 04/Apr/06 09:26 AM   Updated: 09/Apr/06 05:18 AM   Resolved: 09/Apr/06 05:18 AM
Component/s: None
Affects Version/s: 1.0-JSR-4
Fix Version/s: 1.0-JSR-6

Time Tracking:
Not Specified


 Description  « Hide

Let's say I evaluate the following:
key = "actualKey"
map = [key:"value"]
print map

The result will be: {key=value}. What I would like to get is {actualKey=value}

Is this a bug or an intended feature? Basically the key of a map is always interpreted as a string - even if it matches an actual string variable in the scope.

I can use the following workaround, but I feel it's a bit ugly. Are there any better alternatives available?
key = "actualKey"
map = ["$key":"value"]
print map



Guillaume Laforge added a comment - 04/Apr/06 09:37 AM

By default, keys are strings, so when writing map = [key:"value"], it's equivalent to map = ["key":"value"]
If you actually want to use the value of a variable as a key, you have to put the key between parentheses: map = [(key):"value"]


Ryan Misek added a comment - 05/Apr/06 02:39 PM

The solution we used for this (not very Groovyish but ...) was:

def key = "acutalKey"
map.put(key,"value")

Until reading the first comment, I never thought about forcing the evaluation of the key variable by enclosing it in parens.