Closures in Java: another proposal
I am glad that none of the proposals for Closures have been chosen for Java 7. If you don't know, their code names are: BGGA, CICE, and FCM. Why? Because they all suck. Here is my proposal: to introduce alternative syntax for defining an anonymous inner class that extends Object and implements an interface with only one method, with the following construct:
{ arg1, arg2,... argN => statements; }
or { statements; }
if the method doesn't have any parameters.Example 1:
SwingUtilities.invokeLater({field.setText("Hello");})
which is equivalent to:
SwingUtilities.invokeLater(new Runnable() {
public void run(){
field.setText("Hello");
}
});
Example 2:
List<String> list = ...;
Collections.sort(list, {a, b => return a.compareToIgnoreCase(b);});
which is equivalent to:
List<String> list = ...;
Collections.sort(list, new Comparator<String, String>() {
public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
});