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);
}
}
}
A closure is a function (or method) that refers to free variables in their lexical context. The function is a block of code with parameters. It may produce a result value (return type). A free variable is an identifier used but not defined by the closure. It can be used without being a method or a class.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Java does not have closures.
A closure is a programming technique that allows variables outside of the scope of a function to be accessed. Usually, a closure is created when a function is defined in another function, allowing the inner function to access variables in the outer one.
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 returning Number
(and assigns it to parameter block
)
It then creates a Comparator<T>
out of it. This it does by implementing the compare
method by delegating it to a call to block
.
Passes this comparator to the Collections.sort
method.
Here comes a break down of the syntax:
public static <T> void sort(List<T> l, final {T, T=>Number} block) {
^^^^^^^^^^^^^^^^^^^^
An argument called block
which is of type "function that takes two T
and returns a Number
".
Collections.sort(l, new Comparator<T>() {
public int compare(T arg0, T arg1) {
...
}
}
}
An ordinary call to Collections.sort
with an instance of an anonymous subclass of Comparator
as second argument...
...
return block.invoke(arg0, arg1);
...
...which returns the number computed by the function defined by the block
argument.
Put in terms of classical Java, your snippet would correspond to something like
interface Block<T> {
public int invoke(T arg1, T arg2);
}
class Test {
public static <T> void sort(List<T> l, final Block<T> block) {
Collections.sort(l, new Comparator<T>() {
public int compare(T arg0, T arg1) {
return block.invoke(arg0, arg1);
}
});
}
}
As @axtavt points out, Java 7 is (unfortunately) not going to have closures. However, Groovy does, runs on the JVM, and integrates very nicely with other Java code. I'd read this for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With