Show List

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.

  1. 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:

    python
    Copy code
    def greet(name) { println "Hello, $name!" } greet("John Doe") // outputs: "Hello, John Doe!"

    Functions in Groovy can return values using the return keyword. For example:

    scss
    Copy code
    def square(x) { return x * x } def result = square(10) // result = 100
  2. Closures: 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:

    java
    Copy code
    def multiply = { x, y -> x * y } def result = multiply(10, 5) // result = 50

    Closures can also access variables in the enclosing scope, making it possible to write code like this:

    java
    Copy code
    def 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


  • captcha text