Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: Nested evaluation of variables inside ${}

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.

like image 529
user462982 Avatar asked Jun 11 '12 09:06

user462982


People also ask

How do I use a variable inside a string in Groovy?

In Groovy, we can also use ${Variable _name} and $Variable_name instead of using the '+' operator. Using $Variable_name is known as interpolation. It can be used only when the string is defined inside the double quotes.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

What is ${} in Groovy?

String interpolation. Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings. Interpolation is the act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are surrounded by ${} .

How do you comment multiple lines in Groovy?

Comments are used to document your code. Comments in Groovy can be single line or multiline. Multiline comments are identified with /* in the beginning and */ to identify the end of the multiline comment.


1 Answers

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.

like image 148
Dave Newton Avatar answered Oct 24 '22 09:10

Dave Newton