Recursion in Groovy

Our example demonstrates recursion, a technique where a function calls itself. Here’s a classic example:

// This fact function calls itself until it reaches the
// base case of fact(0).
def fact(int n) {
    if (n == 0) {
        return 1
    }
    return n * fact(n - 1)
}

// In the main method, we'll test our recursive function
static void main(String[] args) {
    println(fact(7))

    // Closures can also be recursive, but this requires the
    // closure to be declared before it's defined.
    def fib

    fib = { int n ->
        if (n < 2) {
            return n
        }

        // Since fib was previously declared, Groovy
        // knows which closure to call with fib here.
        return fib(n - 1) + fib(n - 2)
    }

    println(fib(7))
}

To run the program, save it as Recursion.groovy and use the groovy command:

$ groovy Recursion.groovy
5040
13

This example demonstrates two types of recursion:

  1. A traditional recursive function (fact) that calculates the factorial of a number.
  2. A recursive closure (fib) that calculates Fibonacci numbers.

In Groovy, closures are first-class citizens and can be assigned to variables, passed as arguments, and returned from methods. This makes it possible to create recursive closures, as shown in the fib example.

Note that when creating a recursive closure, you need to declare the variable before defining the closure, so that the closure can reference itself.

Recursion can be a powerful technique, but it’s important to use it judiciously, as deeply nested recursive calls can lead to stack overflow errors. In many cases, an iterative solution might be more efficient and easier to understand.