Tag Archives: Closure

Closure in Java

According to Tom Hawtin

A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.

In programming languages, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.

Pasted from <http://en.wikipedia.org/wiki/Closure_%28computer_science%29>

 JSR Proposal: Closures for Java

Summary: Add support so programs can operate on an arbitrary block of code with parameters, and simplify the use of methods that receive such blocks.

This JSR provides support for operating on an arbitrary “block of Java code”, or body, which is either a statement list, an expression, or a combination of both. We call the mechanism a closure expression. Wrapping statements or an expression in a closure expression does not change their meaning, but merely defers their execution. Evaluating a closure expression produces a closure object. The closure object can later be invoked, which results in execution of the body, yielding the value of the expression (if one was present) to the invoker. A closure expression can have parameters, which act as variables whose scope is the body. In this case the invoker of the closure object must provide compatible arguments, which become the values for the parameters.

In addition, this JSR may support a new invocation statement for methods that accept a closure to simplify their use in common cases.

Pasted from <http://www.javac.info/consensus-closures-jsr.html>

Since Java 1.1, anonymous inner class have provided this facility in a highly verbose manner. They also have a restriction of only being able to use final (and definitely assigned) local variables. (Note, even non-final local variables are in scope, but cannot be used.)

Java SE 8 is intended to have a more concise version of this for single-method interfaces*, called “lambdas”. Lambdas have much the same restrictions as anonymous inner classes, although some details vary randomly.

Lambdas are being developed under Project Lambda and JSR 335.

*Originally the design was more flexible allowing Single Abstract Methods (SAM) types. Unfortunately the new design is less flexible, but does attempt to justify allowing implementation within interfaces.

Pasted from <http://stackoverflow.com/questions/5443510/closure-in-java-7



Bringing Closures to Java 5, 6 and 7 – http://mseifed.blogspot.se/2012/09/bringing-closures-to-java-5-6-and-7.html

Page Visitors: 189