Use bound script param in Groovy gstring

In Groovy you can pass in variables using a Binding when evaluating an expression using GroovyShell.

The code below illustrates this. Except the last use case. An attempt is made to access the bound variable in a gstring directly. Apparently it is only accessible by the actual binding.

b1 = new Binding([name:'world']);

def result = new GroovyShell(b1).evaluate("'Hello ' + name")
assert 'Hello world' == result

result = new GroovyShell(b1).evaluate("'Hello ${b1.name}'")
assert 'Hello world' == result

result = new GroovyShell(b1).evaluate("\"Hello $b1.name\"")
assert 'Hello world' == result

result = new GroovyShell(b1).evaluate("println name; 'Hello world'")
assert 'Hello world' == result

result = new GroovyShell(b1).evaluate("\"Hello $name\"")
assert 'Hello world' == result

println "after ${count++}"

Executing the above results in:

world
Caught: groovy.lang.MissingPropertyException: No such property: name for class: BindTest
groovy.lang.MissingPropertyException: No such property: name for class: BindTest
	at BindTest.run(BindTest.groovy:15)

My puzzler is puzzled. Probably one of those intricacies of scoping?

Further reading
Passing parameters into Groovy script using Binding class

Leave a Reply

Your email address will not be published. Required fields are marked *