## Monday, March 17, 2008

### Closures in java: Fibonacci gets some closure

So, in my previous post I promised an example; it's a simple example. In order to compile it you will need to download the BGGA prototype. You can run it using your installed jre. I'll fiddle with it some more but i wanted to put this one up, so here we go:
`public class FibonacciSequenceWithClosures {    public static void main(String[] args) {        int fib = {int n => fib(n)}.invoke(Integer.parseInt(args));        System.out.println(fib);            }    /**     * Helper method to recursively calculate the      * n-th number in the fibonacci seqeunce.      * @param n     * @return the n-th number     * @throws IllegalArgumentException if you pass in a negative number      */    public static int fib(int n) {        if(n < 0) {            throw new IllegalArgumentException("Must be Postive!");        } else if(n == 1 || n==2) {            return 1;        } else {            return fib(n-1) + fib(n-2);        }    }}`

What's going on here? Let's examine it line by line. First you've got your familiar standard class definition; I declare a variable named fib, I'm sure you're asking the what the heck is
` int fib = {int n => fib(n)}.invoke(Integer.parseInt(args));`
Answer: it's a closure! We'll examine that line closer.
`int fib = { int n => fib(n)}.invoke(Integer.parseInt(args));`
First, we have the parameters that we're passing into the closures, then you see
`int fib = { int n => fib(n)}.invoke(Integer.parseInt(args));`
and you're probably wondering what in god's name that operator is, it's the closure operator! Now, the final piece:
`int fib = { int n => fib(n)}.invoke(Integer.parseInt(args));`
What i'm doing here, is calling the invoke method on the closure itself, and passing in the first argument passed to the program via a command-line argument. Finally, After all this is done, I print the value returned from the closure that i stored in the variable fib and we're done. You'll get a StackOverFlowException if you pass too large a number. I could probably fix this, but this is sufficient for a simplistic example.