Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 11

[ 285 ]

}

binding.innerBlock = { closure ->
closure.delegate = delegate
closure()
println "innerBlock: " + binding.message
}

def shell = new GroovyShell(binding)
shell.evaluate(
""" outerBlock {
innerBlock {
message = "Hello, World!"
}
}
"""
)
println "caller: " + binding.message

In the preceding example, the message variable is set in the innermost block of the
DSL, but we can reference it from the outer block closure, and also from the calling
script. Variables set like this in the binding are global to the script, so care must
be taken to initialize them to default values before referencing them. Otherwise,
subsequent blocks within the DSL will reuse the values. In the following code, the
Hello, World! message value is still set when the second outerBlock is evaluated:


outerBlock {
innerBlock {
message = "Hello, World!"
}
}
outerBlock {
println message
}

The output produced by this will not be what we expected. Setting a default
value for the message in the closure definition for binding.outerBlock will
overcome this.


inner: Hello, World!


outer: Hello, World!


Hello, World!


outer: Hello, World!


caller: Hello, World!

Free download pdf