Can any one please describe this sort of code to understand Java closure.
public static <T> void sort(List<T> l, final {T, T=>Number} block) {
Collections.sort(l, new Comparator<T>() {
public int compare(T arg0, T arg1) {
return block.invoke(arg0, arg1);
}
}
}
Important note: The question was regarding an earlier proposal. This was not the syntax chosen. See this Q/A as a “historical reference”.
This syntax is described in the BGGA-proposal by Gilad Bracha, Neal Gafter, James Gosling, and Peter von der Ahé.
This snippet of code can be described as follows:
It takes as the second argument a function taking parameters
(T, T)and returningNumber(and assigns it to parameterblock)It then creates a
Comparator<T>out of it. This it does by implementing thecomparemethod by delegating it to a call toblock.Passes this comparator to the
Collections.sortmethod.Here comes a break down of the syntax:
An argument called
blockwhich is of type “function that takes twoTand returns aNumber“.An ordinary call to
Collections.sortwith an instance of an anonymous subclass ofComparatoras second argument……which returns the number computed by the function defined by the
blockargument.Put in terms of classical Java, your snippet would correspond to something like