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

The closure scope


Closures have access to variables in their surrounding scope. These can be local variables or parameters passed to a method inside which the closure is defined. Here, we can access the name parameter and the local variable salutation in our closure:

def greeting ( name ) {
    def salutation = "Hello"
    def greeter = { println "$salutation , $name" }
    greeter()
}

when: "we call the greeting method"
    greeting("Dolly")
then:
    "Hello , Dolly" == output()

If the closure is defined within a class method, then the object instance fields are also available to the closure. The field member separator, shown in the following code, is also accessible within the closure:

class ClosureInClassMethodScope {
    def separator = ", "
    def greeting ( name ) {
        def salutation = "Hello"
        def greeter = { println "$salutation$separator$name" }
        greeter()
    }
}

given: "A class with a closure in a method"
ClosureInClassMethodScope greeter = new 
ClosureInClassMethodScope...