Recursion in Groovy
Our example demonstrates recursion, a technique where a function calls itself. Here’s a classic example:
To run the program, save it as Recursion.groovy
and use the groovy
command:
This example demonstrates two types of recursion:
- A traditional recursive function (
fact
) that calculates the factorial of a number. - 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.