Simpler syntax gets into way
September 6th, 2006I am reading Groovy in Action at the moment (via MEAP), today Chapter 4 and 5 arrived (So far a good read, but it offers not much more you’d expect from a good apidoc).
I flipped through chapter 4, as it is much know stuff, but this thing here was so strange that it caught my attention:
For the common case of having keys of type String, one can leave away the string markers (single or double quotes) in a map declaration.
assert [’a':1] == [a:1]
Nice, it comes comes as a side-effect from the pattern syntax, I guess. But it continues like this:
This notations can also get in the way when e.g. the content of a local variable is used as a key. Suppose, you have local variable x with content ‘a’. Since [x:1] is equal to [’x':1], how can we make it being equal to [’a':1]? The trick is that we can force Groovy to recognize a symbol as an expression by putting it inside parentheses.
def x = ‘a’
assert [’x':1] == [x:1]
assert [’a':1] == [(x):1]
Does this really simplify anything? Two things to consider
- Pattern work naturally(?) on strings, so it is nice that they don’t have to wrapped as in Java-regexp, in maps I rarely use strings as keys.
- The syntax of “()”: In patterns this is the group operator - here it is an eval. This I find confusing.
