Skip to content

Instantly share code, notes, and snippets.

@ngandriau
Created July 6, 2013 17:34
Show Gist options
  • Save ngandriau/5940612 to your computer and use it in GitHub Desktop.
Save ngandriau/5940612 to your computer and use it in GitHub Desktop.
surprise when using string variable/constant as Map's key
// Illustration of a side effect when using string variable/constant for map's key
def PROP_NAME = "property name"
def myMap = [PROP_NAME: "a Value"]
//assert myMap.keySet().iterator().next() == "property name"
// fails at runtime but it compiles.
// I was expecting the value of the variable to be the key, but it is in fact a String with the name of the variable
assert myMap.keySet().iterator().next() == "PROP_NAME"
// working way: put the variable/constant in parentheses to have expected behavior
myMap = [(PROP_NAME): "a Value"]
assert myMap.keySet().iterator().next() == "property name"
// Second example with ENUM instead of variable/constant
enum MY_ENUM{
ENUM_ONE, ENUM_TWO
}
//myMap = [MY_ENUM.ENUM_ONE: "blabla"]
// fails at compilation
// error message:
//Groovyc: illegal colon after argument expression;
//solution: a complex label expression before a colon must be parenthesized
//good way, add parentheses
myMap = [(MY_ENUM.ENUM_ONE): "blabla"]
assert myMap.keySet().iterator().next() == MY_ENUM.ENUM_ONE
@jxc876
Copy link

jxc876 commented Apr 22, 2015

A bit surprised by this behavior, but the parentheses seems to do the trick!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment