Created
July 6, 2013 17:34
-
-
Save ngandriau/5940612 to your computer and use it in GitHub Desktop.
surprise when using string variable/constant as Map's key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A bit surprised by this behavior, but the parentheses seems to do the trick!