Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 90 ]

The effect of this is that whenever we need to execute a locked segment of code,
we simply wrap the segment in a locked closure block, as follows:


locked {
println "Closure called"
}

In a small way, we are already writing a mini DSL when we use these types on
constructs. This call to the locked method looks, to all intents and purposes, like
a new language construct; that is, a block of code defining the scope of a locking
operation. We will be using this again and again in our DSL examples later in
this book.


When writing methods that take other parameters in addition to a closure, we
generally leave the Closure argument till last. As already mentioned in the previous
section, Groovy has a special syntax handling for these methods, and allows the
closure to be defined as a block after the parameter list when calling the method:


def closureMethodInteger(Integer i, Closure c) {
println "Line $i"
c.call()
}

when: "we invoke a method that accepts an Integer and a Closure"
closureMethodInteger(1) {
println "Line 2"
}
then: "the Closure passed in was executed with the parameter"
"""Line 1
Line 2""" == output()

Forwarding parameters


Parameters passed to the method may have no impact on the closure itself, or
they may be passed to the closure as a parameter. Methods can accept multiple
parameters in addition to the closure. Some may be passed to the closure, while
others may not:


def closureMethodString(String s, Closure c) {
println "Greet someone"
c.call(s)
}

http://www.ebook3000.com
Free download pdf