A closure in Groovy is an anonymous chunk of code that may take arguments,
return a value, and reference and use variables declared in its surrounding
scope. In many ways it resembles anonymous inner classes in Java, and
closures are often used in Groovy in the same way that Java developers use
anonymous inner classes. However, Groovy closures are much more powerful
than anonymous inner classes, and far more convenient to specify and use.
In functional language parlance, such an anonymous code block might be
referred to as an anonymous lambda expression in general or lambda
expression with unbound variables or a closed lambda expression if it didn't
contain references to unbound variables (like threshold in the earlier
example). Groovy makes no such distinction.
Strictly spoken a closure can't be defined. You can define a block of code
that refers to local variables or fields/properties, but it becomes a
closure only when you "bind" (give it a meaning) this block of code to
variables. The closure is a semantic concept, like an instance, which you
cannot define, just create. Strictly spoken a closure is only a closure if
all free variables are bound. Unless this happens it is only partially
closed, hence not really a closure. Since Groovy doesn't provide a way to
define a closed lambda function and a block of code might not be a closed
lambda function at all (because it has free variables), we refer to both as
closure - even as syntactic concept. We are talking about it as syntactic
concept, because the code of defining and creating an instance is one, there
is no difference. We very well know that this terminology is more or less
wrong, but it simplifies many things when talking about code in a language
that doesn't "know" the difference.
See http://groovy.codehaus.org/Closures for more details.
Thanks,
Ajith.
On Feb 11, 2008 5:00 PM, <snanub...@gmail.com> wrote:
> Hi,
> What is the purpose of 'Closure' in Groovy ?
> We are just defining it and calling it , like a normal function.
> Anyone, Please clarify my doubt.
> Thanks,
> Sridevi.