/*
Closures
A Groovy Closure is like a "code block" or a method pointer. It is a piece of
code that is defined and then executed at a later point.
More info at: http://www.groovy-lang.org/closures.html
*/
//Example:
def clos = { println "Hello World!" }
println "Executing the Closure:"
clos()
//Passing parameters to a closure
def sum = { a, b -> println a+b }
sum(2,4)
//Closures may refer to variables not listed in their parameter list.
def x = 5
def multiplyBy = { num -> num * x }
println multiplyBy(10)
// If you have a Closure that takes a single argument, you may omit the
// parameter definition of the Closure
def clos = { print it }
clos( "hi" )
//anonymous block of code
class Example {
static void main(String[] args) {
def clos = {println "Hello World"};
clos.call();
}
}
// formal parameter in closure
class Example {
static void main(String[] args) {
def clos = {param->println "Hello ${param}"};
clos.call("World");
}
}
//Closure and Variables
class Example {
static void main(String[] args) {
def str1 = "Hello";
def clos = {param -> println "${str1} ${param}"}
clos.call("World");
// We are now changing the value of the String str1 which is referenced in the closure
str1 = "Welcome";
clos.call("World");
}
}
//Closure in Methods
class Example {
def static Display(clo) {
// This time the $param parameter gets replaced by the string "Inner"
clo.call("Inner");
}
static void main(String[] args) {
def str1 = "Hello";
def clos = { param -> println "${str1} ${param}" }
clos.call("World");
// We are now changing the value of the String str1 which is referenced in the closure
str1 = "Welcome";
clos.call("World");
// Passing our closure to a method
Example.Display(clos);
}
}
No comments:
Post a Comment