418 APPENDIX B: Introduction to Groovy
A closure always has at least one argument, which will be available within the body of the closure via
the implicit parameter it if no explicit parameters are defined. The developer never has to declare
the it variable—like the this parameter within objects, it is implicitly available. If a closure is invoked
with zero arguments, then it will be null.
Explicit Declaration of Closure
All closures defined in Groovy are essentially derived from the type Closure. Because groovy.lang
is automatically imported, you can refer to Closure as a type within your code. This is an explicit
declaration of a closure. The advantage of declaring a closure explicitly is that a nonclosure cannot
be inadvertently assigned to such a variable. Listing B-32 illustrates how to declare a closure
explicitly.
Listing B-32. Explicit Declaration of a Closure
Closure closure = { println it }
Reusing the Method as a Closure
Groovy provides the method closure operator (.&) for reusing the method as a closure. The method
closure operator allows the method to be accessed and passed around like a closure. Listing B-33
illustrates this.
Listing B-33. Reusing the Method as a Closure
- def list = ["A","B","C","D"]
- String printElement(String element) {
- println element
- }
- list.each(this.&printElement)
Listing B-33 creates a list of names and iterates through the list to print out the names. In line 5, the
method closure operator (.&) causes the method printElement to be accessed as a closure. Here is
the output:
A
B
C
D