Groovy: Nested evaluation of variables inside ${}
Asked Answered
R

1

6

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.

Recur answered 11/6, 2012 at 9:21 Comment(1)
#46327420 seems like a genuine use case for variables.Heresy
R
4

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.

Reeher answered 11/6, 2012 at 10:1 Comment(2)
Nope, your answer perfectly suits my needs. I am just not used too much to string hacking and partly blind for easy solutions. ThanksRecur
How would this work for fieldNames = "name"? I just get null output in that case.Aceae

© 2022 - 2024 — McMap. All rights reserved.