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 } } ) CThread down = new CThread( { ["three","two", "one", "liftoff"] each { sleep(100) println ...

Get Groovy for Domain-specific Languages - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.