What is a closure?
Closures are such an unfamiliar concept to begin with that it can be hard to grasp initially. Closures have characteristics that make them look like a method in so far as we can pass parameters to them and they can return a value. However, unlike methods, closures are anonymous. A closure is just a snippet of code that can be assigned to a variable and executed later:
def flintstones = ["Fred","Barney"] def greeter = { println "Hello, ${it}" } flintstones.each( greeter ) greeter "Wilma" greeter = { } flintstones.each( greeter ) greeter "Wilma"
Because closures are anonymous, they can easily be lost or overwritten. In the preceding example, we defined a variable greeter
to contain a closure that prints a greeting. After greeter
is overwritten with an empty closure, any reference to the original closure is lost.
Tip
It's important to remember that greeter
is not the closure. It is a variable that contains a closure, so...