Groovy Closures
Groovy supports closures and they are very useful when we create Groovy applications.
The most important difference between a normal function/method and a Closure is that Closures can be passed onto other functions as arguments and they serve as Callbacks to the calling function.
For example we can pass closures as arguments to methods to execute them. We can create closures ourselves, but we can also convert a method to a closure with the .& operator. And we can use the converted method just like a normal closure. Because Groovy can use Java objects we can also convert a Java method into a closure.
syntax to write Closure-
[[code]]czozMTM6XCJkZWYgY2xvc3VyZTEgPSB7cGFyYW1zIC0mZ3Q7DQovL3N0YXRlbWVudHMgJmFtcDsgbG9naWMNCn0NCjxzdHJvbmc+ZS57WyYqJl19Zy08L3N0cm9uZz4NCi8vdHlwZSAxwqAgLSBjbG9zdXJlIHdpdGhvdXQgYW55IHBhcmFtZXRlcg0KZGVmIGNsb3N1cmUyID0gew0KwntbJiomXX2gwqDCoMKgcHJpbnRsbiBcIlRlc3QgT25seVwiDQp9DQovL3R5cGUgMiDigJMgY2xvc3VyZSB3aXRoIHR3byBwYXJhbQ0KZGVmIGNsb3N7WyYqJl19dXJlMyA9IHsgU3RyaW5nIG5hbWUsIGludCBhZ2UgLSZndDsNCsKgwqDCoCBwcmludGxuIFwiTXkgbmFtZSBpcyA6ICRuYW1lIGFuZCB7WyYqJl19YWdlIGlzOiAkYWdlXCINCn1cIjt7WyYqJl19[[/code]]
A Closure is usually defined within the braces
{… }. Parameters defines the list of parameters that are to be passed for the closure. The symbol '->' is used to separate the Arguments with the set of statements in the Closure Definition.call a Closure Definition-
Like ‘this’ keyword which refers to the current object, there is ‘it’ keyword which, when used within a Closure Definition refers to the default first parameter being passed to the method. The following code will prove that,
def closure4 = {
println it
}
Closure4.call("Test Again")
Closure4.call()
<em>Output--</em>
Test Again
nullJava method to groovy closure








