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.
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.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
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 ${} .
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.
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.
obj
be an actual map, not a closure, and[]
access on the field namedef 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With