Lazy GString evaluation in Groovy closures -


i try understand why in following snippet, gstring evaluated fine if it's created inside closure, throw exception if try create string outside , try evaluate inside closures:

map1 = ['foo': 1, 'bar': 2] map2 = ['foo': 3, 'bar': 4]  dynamicallygeneratedstring = "key1: ${->key1}, val1: ${->value1}, key2: ${->key2}, val2: ${->value2}"  map1.each { key1, value1 ->     map2.each { key2, value2 ->         println "key1: ${->key1}, val1: ${->value1}, key2: ${->key2}, val2: ${->value2}" // works expected         // println dynamicallygeneratedstring // throws missingpropertyexception     } } 

the desired output in both cases be:

key1: foo, val1: 1, key2: foo, val2: 3 key1: foo, val1: 1, key2: bar, val2: 4 key1: bar, val1: 2, key2: foo, val2: 3 key1: bar, val1: 2, key2: bar, val2: 4 

my goal dynamically generate string depending on other conditions, , lazily evaluate contents while looping through maps.

is valid approach @ all?

the problem is, when create gstring, stores references variables. when try evaluate it, refernces point nothing , exception.

if want way, think have use template engine with

println new groovy.text.gstringtemplateengine().createtemplate(dynamicallygeneratedstring).make(key1: key1, value1: value1, key2: key2, value2: value2) 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -