Book Image

Groovy for Domain-Specific Languages, Second Edition

By : Fergal Dearle
Book Image

Groovy for Domain-Specific Languages, Second Edition

By: Fergal Dearle

Overview of this book

Table of Contents (20 chapters)
Groovy for Domain-specific Languages Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Free Chapter
1
Introduction to DSLs and Groovy
Index

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 it
        }
    } )

Here we define a subclass of the Java Thread class, which can be constructed with...