Java 7 : Oracle pushes a first version of closures

2 days ago, Oracle pushed a first version of the closures implementation. We can see the evolving syntax in the test cases they made for the Java compiler. You can see these test cases here.

This revision supports the following features (copied from revision) :

  • Function types syntax
  • Function types subtyping
  • Full support for lambda expression of type 1 and 2
  • Inference of thrown types/return type in a lambda
  • Lambda conversion using rules specified in v0.1.5 draft
  • Support references to 'this' (both explicit and implicit)
  • Translation using method handles

The function types aren't enabled by default, so you have to use -XDallowFunctionTypes to enable it.

Here are some examples of lambda expression of type 1 taken from the test cases :

int i1 = #()(3).(); //i1 = 3
Integer i2 = #()(3).(); //i2 = 3
int i3 = #(int x)( x + 1 ).(3); //i3 = 4
int i4 = #(Number x)(x.intValue()).(new Float(3.0f)); //i4 = 3

And with type 2 :

int i1 = #(){ return 3; }.(); //i1 = 3
Integer i2 = #(){ return 3; }.(); //i2 = 3
int i3 = #(int x){ return x + 1; }.(3); //i3 = 4
int i4 = #(Number x){ return x.intValue(); }.(new Float(3.0f)); //i4 = 3

For those who didn't understand the syntax, #(int x)( x + 1 ) declares a lambda expression that takes a int and return this int plus 1. And the . (dot) is used to invoke the lambda expression. So #(int x)( x + 1 ).(3) declares the lambda expression and invoke it with 3 as parameter.

This syntax is a little bit shocking, but I think we'll get used.

Related articles

  • State of the Lambda
  • Java 7 has been released!
  • Java 7 : Add "public defender methods" to Java interfaces
  • Java 7 Delays and Plan B
  • Java 7 : Languages updates from Project Coin
  • Java SE 6 Update 21 Released
  • Comments

    Comments powered by Disqus