Closures and lambda expressions in Groovy

Closures and lambda expressions are used in Groovy to define anonymous functions that can be used as values or passed as arguments to other functions. Here’s how to use closures and lambda expressions in Groovy:

1. Closures: A closure is a block of code that can be treated as a value, assigned to a variable, and passed as an argument to a function. In Groovy, you can define a closure using the `->` operator, as shown in the following example:

def square = { x -> x * x }

println(square(2))

In this example, we define a closure called `square` that takes one argument `x` and returns the square of `x`. We then call the `square` closure with an argument of `2` and print the result to the console.

2. Lambda expressions: A lambda expression is a shorter syntax for defining closures, using the `->` operator and omitting the parameter list when there is only one parameter. In Groovy, you can use the `->` operator to define lambda expressions, as shown in the following example:

def numbers = [1, 2, 3, 4, 5]

def evenNumbers = numbers.findAll { it % 2 == 0 }

println(evenNumbers)

In this example, we define a list of numbers from 1 to 5, and then use the `findAll` method to find all the even numbers inthe list. We define a lambda expression using the `->` operator to test whether each number is even, and pass it as an argument to the `findAll` method. The lambda expression uses the implicit parameter `it` to refer to each number in the list.

Closures and lambda expressions are important concepts in Groovy programming, and they allow you to define anonymous functions that can be used as values or passed as arguments to other functions. By using closures and lambda expressions, you can create code that is more concise, readable, and flexible.