Learn Java for Web Development

(Tina Meador) #1

416 APPENDIX B: Introduction to Groovy


Listing B-25. Calling a Closure



  1. def closureVar = {println 'Hello world'}

  2. println "closure is not called yet"

  3. println " "

  4. closureVar.call()


   Line 1: This line has the closure with no parameters and consists of a single
println statement. Because there are no parameters, the parameter List
and the -> separator are omitted. The closure is referenced by the identifier
closureVar.
 Line 4: This line uses the explicit mechanism via the call() method to invoke
the closure. You may also use the implicit nameless invocation approach:
closureVar(). As shown in the output, the closure prints “Hello world” when it is
called in line 4, not when it is defined in line 1.

Here is the output:


closure is not called yet
Hello world


Listing B-26 illustrates the same closure as in Listing B-25 but with the parameter.


Listing B-26. Closure with Parameter



  1. def closureVar = {param -> println "Hello ${param}"}

  2. closureVar.call('world')

  3. closureVar ('implicit world')


   Line 2: This is an explicit call with the actual argument 'world'.
 Line 3: This is an implicit call with the actual argument 'implicit world'.

Hello world
Hello implicit world


As Listing B-27 illustrates, the formal parameters to a closure may be assigned default values.


Listing B-27. Parameters with Default Values



  1. def sayHello= {str1, str2= " default world" -> println "${str1} ${str2}" }

  2. sayHello("Hello", "world")

  3. sayHello("Hello")


   Line 1: The sayHello closure takes two parameters, of which one parameter,
str2, has a default value.
 Line 3: Only one actual parameter is provided to the closure, and the default
value of the second parameter is used.
Free download pdf