Method references (Implementation Issue)
Each method reference is transformed to a closure:
// Math#sqrt(double) will be transformed to { double d => Math.sqrt(d) } { double => double } sqrt = Math#sqrt(double);
Instance method references are transformed in a similar way.
Circle c = new Circle(); { => void } p = c#draw(); // the same as { => c.draw(); }
{ Circle => void } p = Circle#draw(); // { Circle c => c.draw(); }
Let us have a look at another example. We declare class Box
:
public class Box<T> { T v; public Box(T v) { this.v = v; } public T getValue() { return v; } public void print() { System.out.println("Box: " + v); } }
and refer to the print
method:
// Box#print() will be transformed to { Box<Integer> box => box.print(); } { Box<Integer> => void } p = Box#print();
Reference to a generic method will be replaced by a closure as follows:
public class Generic { public static <T> Box<T> copy(Box<T> b) { return new Box<T>(b.getValue()); } }
// Generic#copy(Box<Integer>) will be transformed to // { Box<Integer> box => Generic.copy(box) } { Box<Integer> => Box<Integer> } boxCopy = Generic#copy(Box<Integer>);
I do not want closures in Java because they are not simple.
This argument is wrong. We should always weigh all pros and cons. Closures are not simple. But is software development in Java simple? What should I know to be capable to develop software in Java? Knowledge of the Java programming language is clearly not enough. One should also know some Java technologies and frameworks. And are they simple? Are JPA, EJB, JAX-WS, Hibernate, or Spring (to name a few) simple? Apparently no, so it does not make sense to reject closures just for this reason.