Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


Share this Page URL
Help

Appendix J: Advanced Closures > J.1 Simple Closures - Pg. 421

J.1 simple closures 421 The ideas presented here contribute to the multiparadigm approach that is a feature of Groovy. In this appendix, we demonstrate how ideas from func- tional programming (Thompson, 1999) can be both realized and exploited in Groovy. The functional programming paradigm exploits polymorphism, com- position, and computation patterns through higher-order functions. We shall see how we may apply these ideas successfully in Groovy. J.1 simple closures We have previously described a closure as a code block. The closure can be para- meterized to make it more generally useful, it can be referenced, it can be passed as a method parameter, and it can be invoked with the call message. Example 01 includes a simple parameterized closure entitled multiply that finds the product of two numeric parameters. def multiply = { x, y -> return x * y } println "multiply(3, 4): ${multiply.call(3, 4)}" println "multiply(3.4, 5.6): ${multiply(3.4, 5.6)}" // explicit call // implicit call EXAMPLE 01 Simple closure Executing this program demonstrates the execution of the closures and pro- duces the output: multiply(3, 4): 12 multiply(3.4, 5.6): 19.04 Chapter 9 noted how state may be referenced by closures. In Example 02, we have a multiplier variable that is in scope when the multiply closure is defined. The closure computes the product of its single parameter and the multiplier . EXAMPLE 02 Scoping and closures def multiplier = 2 def multiply = { x -> return x * multiplier } // second operand from enclosing scope println "multiply(3): ${multiply.call(3)}" println "multiply(5.6): ${multiply(5.6)}" // Now do it again but with a different multiplier value multiplier = 3