Home > Uncategorized > Groovy Closures

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-

def closure1 = {params ->
//statements & logic
}
e.g-
//type 1  - closure without any parameter
def closure2 = {
    println "Test Only"
}
//type 2 – closure with two param
def closure3 = { String name, int age ->
    println "My name is : $name and age is: $age"
}

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-

closure1.call( args )
closure1(args )
e.g 

closure2()
closure2.call()
output- 
Test Only
Test Only
-------------------------------------------
closure3("sadhna", 30)
closure3.call("saisha", 3)

output- 
My name is : sadhna and age is: 30
My name is : saisha and age is: 3

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()

Output--
Test Again
null

Java  method  to  groovy closure

public class Test {
 public static void javaTest(final String s) {
  System.out.println("Java --" + s + "!");
 }
}

With the following script we use this Java class and convert the javaTest method to a closure:
// Simple list with names.
def names = ['groovy', 'grails', 'closure']
// Simple closure.
names.each { println 'Closure --' + it + '!' }
// Groovy method to convert to closure.
def groovySays(s) {
 "Groovy --${s}!"
}
// Use .& syntax to convert method to closure.
names.each(this.&groovySays)
// Convert Java method to closure and use it.
def javaTest = Test.&javaTest
names.each javaTest

output-
Closure --groovy!
Closure --grails!
Closure --closure!
Groovy --groovy!
Groovy --grails!
Groovy --closure!
Java --groovy!
Java --grails!
Java --closure!
Categories: Uncategorized Tags: