Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 92 ]

At this point, we can write code that nests the two method calls by calling update
as follows:


locked {
update(customer) { cust ->
cust.name = "Barney"
}
}

This outputs the following result, showing how the update code is wrapped by
updateCustomer, which retrieves the customer object and subsequently saves it.
The whole operation is wrapped by locked, which includes everything within
a transaction:


Transaction lock


Customer name was Fred


Customer name is now Barney


Transaction release


Calling closures


In our previous examples, we were passing closures to the built-in collection
methods. In the examples to date, we have deferred to the collection method to
do the closure invocations for us. Let's now look at how we can make a call to the
closure ourselves. For the sake of this example, we will ignore the fact that the GDK
provides versions of the Thread.start method that achieves the same thing:


class CThread extends Thread {
Closure closure

CThread( Closure c ) {
this.closure = c
this.start()
}
public void run() {
if (closure)
closure() // invoke the closure
}

}

CThread up = new CThread(
{
[1..9]* each {
sleep(10 * it)
println it

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