Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure in Java 7 [closed]

Tags:

java

closures

What is closure? It is supposed to be included in Java 7. (Closures were discussed for inclusion in Java 7, but in the end were not included. -ed) Can anyone please provide me with some reliable references from where I can learn stuff about closures?

like image 879
Swaranga Sarma Avatar asked Mar 26 '11 16:03

Swaranga Sarma


People also ask

What is Java closure?

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.

Is closure available in Java?

Java does not have closures.

Does Java 8 support closures?

In effect, java doesn't have closures at all. One may not notice the difference unless they have used real closures in a language that actually supports them.

Is Java lambda a closure?

Java supports lambda expressions but not the Closures. A lambda expression is an anonymous function and can be defined as a parameter. The Closures are like code fragments or code blocks that can be used without being a method or a class.


2 Answers

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

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.

like image 71
Tom Hawtin - tackline Avatar answered Sep 29 '22 13:09

Tom Hawtin - tackline


Here is Neal Gafter's blog one of the pioneers introducing closures in Java. His post on closures from January 28, 2007 is named A Definition of Closures On his blog there is lots of information to get you started as well as videos. An here is an excellent Google talk - Advanced Topics In Programming Languages - Closures For Java with Neal Gafter, as well.

like image 27
Bartzilla Avatar answered Sep 29 '22 11:09

Bartzilla