Groovy: Nested evaluation of variables inside ${}

groovy, gstring, string

Solution

What about that page makes you think it'd be possible? There aren't any nested examples.

AFAIK it's not possible by default; expressions within `${}` aren't re-evaluated. Which would be dangerous anyway since it'd be really easy to make it infinitely-deep and blow the stack.

In this case, it's not necessary anyway.

- Make `obj` be an actual map, not a closure, and

- Use normal map `[]` access on the field name

def obj = [ "name": "Whatever", "street": "ABC-Street", "zip": "22222" ]
def fieldNames = ["name", "street", "zip"]

fieldNames.each { println "Gimme the value ${obj[it]}" }

Gimme the value  -> Whatever
Gimme the value  -> ABC-Street
Gimme the value  -> 22222

Edit It's possible I misunderstood and you're deliberately making `obj` a closure instead of a map, although I don't understand why.

Problem

I there a way to do nested evaluation of "$-Strings" in Groovy like, e.g. ``` def obj = {["name":"Whatever", "street":"ABC-Street", "zip":"22222"]} def fieldNames = ["name", "street", "zip"] fieldNames.each{ fieldname -> def result = " ${{->"obj.${fieldname}"}}" //can't figure out how this should look like println("Gimme the value "+result); } ``` Result should be: ``` Gimme the value Whatever Gimme the value ABC-Street Gimme the value 22222 ``` My attempts to solve this either don't give proper results (e.g. just obj.street} or won't compile at all. I simply haven't understood the whole concept so far it seems. However, seeing this: http://groovy.codehaus.org/Strings+and+GString I believe it should be possible.

Original source