O'Reilly logo

Groovy for Domain-specific Languages - Second Edition by Fergal Dearle

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ) { ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required