Tutorial by Examples

def addNumbers = { a, b -> a + b } addNumbers(-7, 15) // returns 8
['cat', 'dog', 'fish'].collect { it.length() } it is the default name of the parameter if you have a single parameter and do not explicitly name the parameter. You can optionally declare the parameter as well. ['cat', 'dog', 'fish'].collect { animal -> animal.length() }
A method can be converted to a closure using the & operator. def add(def a, def b) { a + b } Closure addClosure = this.&add assert this.add(4, 5) == addClosure(4, 5)
class MyHello { def sayHello() { "Hello, world" } } def cl = { sayHello() } cl() // groovy.lang.MissingMethodException cl.delegate = new MyHello() cl(); // "Hello, world" Used extensively by Groovy DSLs.
There are frequent behavior patterns that can result in a lot of boilerplate code. By declaring a method that takes a Closure as a parameter, you can simplify your program. As an example, it is a common pattern to retrieve a database connection, start a transaction, do work, and then either commit ...
Let's create a map and a closure to print hello def exMap = [:] def exClosure = { println "Hello" } Assign closure to a property in map exMap.closureProp = exClosure Calling closure exMap.closureProp.call() Output Hello Another Example - Lets create a class with ba...

Page 1 of 1