<< The NetBeans 6.0 Story Continued: Using The Profiler | Home | Happy Chinese New Year >>

Friday Java Quiz: Know Your Closures

The closures are coming!
The closures are coming!!
The closures are coming!!!

And don't let your baby cry out loud.

To celebrate Java's entry into the closures era, today's Java quiz is about closures, specifically the BGGA closures.

Will the following

public class Fib {
  private static {int=>int} fib = {
    int n =>
      n==0 ? 0 :
      n==1 ? 1 :
      fib.invoke(n-1) + fib.invoke(n-2)
  };

  public static void main(String[] args) {
    System.out.println(fib.invoke(6));
  }
}

program compile? Run? If so, what will it print out?

You can bend the rules and actually run the prototype compiler that is available here.



Re: Friday Java Quiz: Know Your Closures

Ah, a trick question. This is about the (existing) definite assignment rules, not closures. But I won't spoil it too much for the rest of your readers by revealing the answer.

Re: Friday Java Quiz: Know Your Closures

Oh, it's not a trick question. I thought "fib" was a local variable.

Re: Friday Java Quiz: Know Your Closures

I predict yes, yes, 8

Re: Friday Java Quiz: Know Your Closures

Hi, Its surely 8 only. Can you please let us know what is the catch point please?

Re: Friday Java Quiz: Know Your Closures

As Neal pointed out, this is not a trick question. I'm just starting to go through the spec, and figured I'd put out a simple example of using the basics of BGGA closures.

I believe there are quite a lot of people out there who have not read the specs yet. Maybe this example will make them think "Hmm, this closure thing isn't that scary. I can even guess what the code does without reading the spec or running the compiler."

Of all the "new features" introduced in the various JDK releases, such as the JDK 1.1 event model, the JavaBeans events mechanism, reflections, inner classes, generics, static imports, the for each loop, etc., I find closures to be similar in complexity to inner classes, which we absorbed pretty smoothly.

Can you go wild with this stuff, sure. But you can do that with, for example, reflections too. But in the field, most people don't do that sort of thing.

I think generics is the only "new feature" that caused indigestions for a lot of people. I hope after playing with closures for a while I can report back that everything is transparent, and that there is nothing like the "wall of erasure" problem for generics.

Re: Friday Java Quiz: Know Your Closures

NICE job =)

Add a comment Send a TrackBack