Dynamic Map keys in Groovy/Grails

Nothing earth shattering to see here: I answered this question for someone and wanted to share it.

The Question

How do I use a variable to name a map key when using ‘object’ notation instead of .put()?

The Answer

Wrap the name of the key in parenthesis. It’ll become an expression and the result will be stored as the key:

Where it’s -really- handy

Imagine you have a “IProcessor” interface that does something (e.g. format, mangle, turn into pig-latin) to a given type of input. You’d like to build a factory that’ll serve up the appropriate processor for the type.

Why? Because we’re Java folks, and building factories is what we do. Inside it, we can form a registry that relates class types to ‘processors,’ using it as the core of the factory:

Further, because we’re smart Java folks we know we can use the above to configure the factory via Spring, in resources.groovy, instead of hard-coding this stuff into true source code.

Joe Rinehart's been developing software for Web, mobile, and desktop since 1998. While he mainly now works in Java, Grails, and HTML5, he has a long history of community involvement in the Flash, Flex, and ColdFusion space. As a published author and award-winning speaker, he's bringing his skills to CompileDammit to help users new to Grails and Java. When he's not coding, he's either spending time with his family or feeding an appetite for endurance mountain bike racing. (8/9/2012 update: He's now either spending time with his family or getting over a huge knee injury caused by endurance mountain bike racing.)

Posted in Grails for CFML Developers, Groovy/Grails
3 comments on “Dynamic Map keys in Groovy/Grails
  1. Marc Esher says:

    “Because we’re Java folks, and building factories is what we do”.

    It seems you have something in common with the great industrialists of years gone by. Yer a regular Sir Topham Hat!

    (Good tip, too, though it looks like maybe your code sample got swallowed)

  2. lesiki says:

    Hi Joe,

    As far as I can tell, this can be achieved either with the parentheses or using the “${}” (gstring) notation. You don’t need to use both.

    Or am I missing a subtle difference?

  3. Joe Rinehart says:

    Lesiki: For string keys, you’re entirely right. For the class-based example, the parens are necessary or you’ll wind up with a string-based key that is the classname.

Leave a Reply

Your email address will not be published. Required fields are marked *