language has been requested for a long time. JSR-335, Lambda Expressions for the Java Programming
Language, which aims to support programming in a multicore environment by adding closures and
related features to the Java language, was scheduled to be included in JSE 8. However, if you want to
enjoy the benefits that closures bring to your application, you need to use a scripting language like
Groovy, Python, Scala, Ruby, Clojure, and so on.
Listing 22-5 shows a very simple example of using closures (the file name is SimpleClosure.groovy)
in Groovy.
Listing 22-5. A Simple Closure Example
package com.apress.prospring3.ch22.groovy.closure
def names = ['Clarence', 'Johnny', 'Mary']
names.each {println 'Hello: ' + it}
In Listing 22-5, a list is declared. Then, the convenient each() method is used for an operation that
will iterate through each item in the list. The argument to the each() method is a closure, which is
enclosed in curly braces in Groovy. As a result, the logic in the closure will be applied to each item within
the list. Within the closure, it is a special variable used by Groovy to represent the item currently in
context. So, the closure will prefix each item in the list with the String "Hello: " and then print it.
Running the script will produce the following output:
Hello: Clarence
Hello: Johnny
Hello: Mary
As mentioned, a closure can be declared as a variable and used when required. Another example is
shown in Listing 22-6 (the file name is ClosureOnMap.groovy).
Listing 22-6. Define a Closure as Variable
package com.apress.prospring3.ch22.groovy.closure
def map = ['a': 10, 'b': 50]
Closure square = {key, value -> map[key] = value * value}
map.each square
println map
In Listing 22-6, a map is defined. Then, a variable of type Closure is declared. The closure accepts
the key and value of a map's entry as its arguments, and the logic calculates the square of the value of the
key. Running the program will produce the following output:
[a:100, b:2500]
This was just a simple introduction to closures. In the next section, we will develop a simple rule
engine using Groovy and Spring. Closures will be used also. For a more detailed description of using
closures in Groovy, please refer to the online documentation at http://groovy.codehaus.org/JN2515-
Closures.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home