Tuesday, January 12, 2010

Java Lambda Expressions / Closures

Lambda expressions are just (anonymous) functions.



f(x) = x can be expressed as x→x
f(x, y) = x*x + y*y can be expressed as x, y→x*x + y*y

In simple Java terms,


1. Return an int 23 with a void argument



int j = { => 23 }.invoke();

2. Closure with 1 argument, convert 23 kilograms to pounds



double j = { double kilograms => kilograms*2.2D }.invoke(23);

3. Closure with 2 arguments, get the sum of the 2 squares



int squareSum = { int x, int y => (x*x) + (y*y) }.invoke(2,3);

4. Closure returning an instance and invoking an instance method



{ new RocketLauncher() }.invoke().fire();

Every time a closure is created at compile time, an interface is automatically created for each expression having an invoke method with a signature depending on the number of arguments, then an anonymous subclass of this interface is constructed.


Enjoy!