Groovy Closure Application Details

In Groovy, a Closure is a concept similar to an anonymous function. It is a block of code that can be passed as an argument to a method or assigned to a variable, and it can access and modify variables within its defining scope. Closures are widely used in Groovy for scenarios such as collection operations, functional programming, and event-driven programming.

The following example demonstrates the definition and usage of Closures in Groovy:

def square = { x -> x * x }
println(square(2)) // Output: 4

def nums = [1, 2, 3, 4, 5]
def evenNums = nums.findAll { it % 2 == 0 }
println(evenNums) // Output: [2, 4]

def sum = { x, y -> x + y }

def apply(Closure closure, a, b) {
    closure(a, b)
}

println(apply(sum, 2, 3)) // Output: 5

In the example above, we first define a square Closure that accepts a parameter x and returns the square of x. We then use the square Closure to calculate the square of 2 and print the result. Next, we define an integer array nums and use the findAll method along with a Closure to filter out even numbers from it, printing the resulting list. Finally, we define a sum Closure that accepts two parameters, x and y, and returns their sum. We then define an apply method that accepts a Closure and two arguments, passes these arguments to the Closure for computation, and returns the result.

It is important to note that in Groovy, Closures can be defined using {} or (), or using ->; they have the same effect. A Closure can access variables within its defining scope. If you need to modify such variables, you must declare them using the def keyword. Additionally, Groovy provides many methods for Collections and functional programming that utilize Closures, such as each, collect, findAll, groupBy, and inject.