Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 106 ]

}
}

given: "A class with a closure in a method"
ClosureInClassMethodScope greeter = new
ClosureInClassMethodScope()
when: "we call the class method"
greeter.greeting "Dolly"
then:
"Hello, Dolly" == output()

In addition to directly accessing variables, we can also use GStrings to paste variables
from the local scope into a string.


In essence, the closure simply inherits all of the visible variables and fields from the
surrounding scope in which it is defined. The closure can update any of these fields
or variables, and the class or local method scope will see these changes. Likewise,
any changes that occur in the class or method scope will also be seen by the closure.


Unlike the regular method or class scope, we are able to pass a closure back from a
method. At the time that a closure is defined, Groovy binds all of the variables that it
accesses to the closure object. When this happens, Groovy converts any stack-based
variables such as method parameters and local variables into heap-based duplicates
of these objects. The values of these objects are now bound to the individual closure
because the original values were lost once the method was returned. Take the
following example, which illustrates this:


class MethodReturningClosure {
def member = "first"
def method (String param ) {
def local = member
return {
"Member: $member Local: $local Parameter: $param"
}
}
}

given: "we have a class with a method returning a closure"
MethodReturningClosure myClazz = new MethodReturningClosure()
when: "we invoke the method"
def clos1 = myClazz.method("first")
then: "member and stack variables are bound to the closure"
clos1() == "Member: first Local: first Parameter: first"
when: "we invoke again we get a new closure"

http://www.ebook3000.com
Free download pdf