Wednesday, April 23, 2008

What are Groovy Closures?

One of the more difficult concepts that I had to get my head around as a Java developer was the concept of Groovy closures.

Closures:
  • are classes (defined by Closure.class)
    • like defining new Closure() {}
  • are similar to anonymous classes
  • are defined with braces { and }
  • provide one default iterator parameter (if none specified) called "it" for iterator
    • (1..3).each {println "number $it" }
  • can accept parameters
    • (1..3).each {someNum -> println "Some number $someNum" }
  • can be predefined with a variable name and invoked (they are classes after all)
    • def myClosure = {x, y -> println "you sent $x and $y" }
    • myClosure 'Feet', 'Hans'
    • prints: you sent Feet and Hans
  • do not require an input parameter if its not used, do not provide one
    • def myClosure = { -> "returning this dude" }
    • println myClosure

No comments: