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

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.