Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


Code Block
printMapClosure = { key, value -> println key + "=" + value }
[ "yueYue" : "wuWu", "laneMark" : "burksWilliams", "sudha" : "saseethiaseeleethialeselanKumari" ].each(printMapClosure)


Code Block

More Closure Examples

Here are a few more closure examples. This first one shows a couple of things. First, the closure is interacting with a variable outside itself. That is, the closure's purpose is to put together the parts of a stock order held in the array orderParts, by adding (appending) it to the variable fullString. The variable fullString is not in the closure. The second thing that is different about this example is that the closure is "anonymous", meaning that it is not given a name, and is defined in the place where the each method is called.


The next example is another anonymous closure, this time, summing up the values stored in a map.

Code Block
myMap = ["asdfChina": 1 , "qwerIndia" : 2, "sdfgUSA" : 103]

result = 0
myMap.keySet().each( { result+= myMap[it] } )
println result