A closure is like an anonymous function in javascript. If you familiar with javascript, the closure is not hard to understand.

The closure also called lambda which first introduced in Lisp. All the dynamic languages like javascript, list, ruby, groovy are based on the concept of lambda calculus. They also called functional programming languages.

In these languages , function is the first class, and the closure is nothing but an anonymous function. Function can be passed as a parameter or return as a return value just like any variable.

The anonymous function is the most interesting function in these languages, its also the topic of this post which talking about groovy.

An common usage of closure is apply on collection.

def fruits = ["apple","peach"]
fruits.each {
    println "This is a ${it}"

The each method takes a closure as parameter, the implicit variable "it" represent the element in the collection. The closure can accept parameter, when the parameter number is one, you can use the it to represent it without explicitly define the parameter.

The each method actually is added to java.lang.Object as an augments to the standard JDK.

Object each(Closure closure) 

So the equivalent form should be.

fruits.each( { println "This is a ${it}" })

Groovy provide a syntax sugar that when last parameter is a closure, the closure can be defined anonymously after the call parenthesis.

Closure parameters

We already mentioned that the only one parameter can be represented by "it". The closure can also accept multiple parameter, the syntax may looks a bit wired .

def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" } 

The code before -> is the parameter list separated with comma, the closure block followed.