How to Work with Closures in Groovy

  • google plus

In Brief...

A common challenge in data processing is to pass a method as a parameter to another method. For example, we might have a method that we wish to call to print the results of a calculation. The calculation itself is passed as a method, and that method contains the logic to implement the calculation. Therefore, if we wish to perform addition, subtraction, multipliation and division, we need to create four methods that perform the necessary arithmetic. With closures, however, we can do away with building those four methods! That will save us development time and cut down on debugging effort as well. How do we pull of this feat of "magic"? With closures!

In this topic you will implement the scenario presented above without coding extra methods.

Instructions

To learn how to use closures in Groovy follow these 3 steps:

  1. Open your text editor and type in the following lines of Groovy code:
    
    // Work with closures in Groovy
    mathMethod ("add", 20, 10, { op1, op2 -> return op1 + op2})
    mathMethod ("subtract", 20, 10, { op1, op2 -> return op1 - op2})
    mathMethod ("multiply", 20, 10, { op1, op2 -> return op1 * op2})
    mathMethod ("divide", 20, 10, { op1, op2 -> return op1 / op2})
    
    def static mathMethod (String operation, int i, int j, mathClosure) {
    	println("The result of the $operation operation: ${mathClosure(i, j)}")
    }
    The method that will perform and print the results of the calculation is mathMethod. Note the third argument of the method, mathClosure. The closure passed to the method determines the arithmetic operation to perform. Consider the 4 method calls to mathMethod. Each one contains a closure as the third parameter. The clsoure is enclosed in curly braces and begins with the operands that will be used by the logic of the closure. In this case, each closure will perform an add, a subtract, a multiply or divided operation. The closure logic is actually executed by the mathMethod within the print statement.
  2. Save your file as WorkWithClosures.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run closures script
    The output displays the result of executing each closure.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss