JDK-6315058 : Anonymous functions
  • Type: Enhancement
  • Component: specification
  • Sub-Component: language
  • Affected Version: 6
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2005-08-24
  • Updated: 2010-04-04
  • Resolved: 2006-11-14
Related Reports
Duplicate :  
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
I am suggesting an "anonymous function" enhancement to the Java language specification which would be similar to the anonymous class concept.  It would allow shorter and more readable code without extra complication.

Often I have final static members which need more complex initialisation that a simple "new MyObject();"

For example, they might need a sequence of operations, or an exception to be caught.

I typically have to write:

public static final MyObject SINGLETON = createSingleton();
private static final MyObject createSingleton() {
    try {
        // Do further initialisation such as building up arrays
        MyObject obj = new MyObject(array);
        // Do some more stuff
        return obj;
    } catch (SomeException e) {
        throw new ExceptionInInitializerError(e);
    }
}



I would like to write:

public static final MyObject SINGLETON = {
    try {
        // Do further initialisation such as building up arrays
        MyObject obj = new MyObject(array);
        // Do some more stuff
        return obj;
    } catch (SomeException e) {
        throw new ExceptionInInitializerError(e);
    }
};


This could also be applied to general inline code.  Often one has to declare final variables before referring to them in a new anonymous class such as an ActionListener or WindowAdapter.  But sometimes these final variables need complex conditional initialisation leading to messy code.

For example, the following demonstrates an "anonymous function" used inline to establish a final parameter to a new ActionListener:


public void doStuff() {

    // a must be final because it is referred to in the listener anon inner class
    final int myVar = {
        // do lots of conditional processing and/or exception handling
        if (test) return x;
        if (other test) return y;
        if (a & !b) return z;
        return -1;
    }
    
    component.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // Refer to final variable 'myVar'
            callSomeFunction(myVar, e.getSource());
        }
    }
}


JUSTIFICATION :
Better code clarity

Comments
EVALUATION This is really a request for closures.
14-11-2006