Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 5

[ 105 ]

2
}
expect:
closure(1) == 1 // return statement reached
closure(-1) == 2 // ending statement evaluates to 2

If no return statement is encountered, then the value returned by the closure is the
result of evaluating the last statement encountered in the closure block. If the last
statement has no value, the closure will return null:


void voidMethod() {
}
given: "a closure returning void method"
def nullReturn = { voidMethod() }
expect:
nullReturn() == null

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()
Free download pdf