Functions and closures in Groovy
Functions and closures are an important part of Groovy, providing a way to organize code into reusable and composable building blocks.
Functions: Functions in Groovy are declared using the
def
keyword, followed by the function name, arguments in parentheses, and the function body in curly braces. For example:pythonCopy codedef greet(name) { println "Hello, $name!" } greet("John Doe") // outputs: "Hello, John Doe!"Functions in Groovy can return values using the
return
keyword. For example:scssCopy codedef square(x) { return x * x } def result = square(10) // result = 100Closures: Closures in Groovy are anonymous functions that can be stored in variables, passed as arguments to other functions, or returned as values from functions. Closures can access variables in the enclosing scope, making them a powerful tool for writing concise and expressive code. For example:
javaCopy codedef multiply = { x, y -> x * y } def result = multiply(10, 5) // result = 50Closures can also access variables in the enclosing scope, making it possible to write code like this:
javaCopy codedef factor = 2 def multiply = { x -> x * factor } def result = multiply(10) // result = 20
These are just a few examples of the power and flexibility of functions and closures in Groovy. When used effectively, they can make code easier to write, understand, and maintain, making Groovy a great choice for many types of projects.
Leave a Comment