27 Jan 2005 06:13
Re: [groovy-dev] Re: Closure syntax [[ was [groovy-dev] Pragmatic Groovy Development and Project Management ]]
Martin C. Martin wrote:
> How's this:
>
> { statements } is a block. It's just like a Java block, except it can
> return a value, and it's a first class object. So in the following,
> they're all blocks:
>
> mylist.each { println it }
> mylist.collect { it * it }
> mylist.findAll { it.length > 5 }
>
> In this case, "it" is bound in the function "each," "collect" or
> "findAll," before they execute the block.
Ruby has a special mechanism for binding a block/closure to a method.
Though given that we support optional static typing and expose typesafe
bytecode - we have to pass the closure as a regular Java parameter -
rather than having some magical 'block binding'.
So maybe being explict that the block/closure is passed as a parameter
is the easiest explanation.
> To turn it into a quick, anonymous function, we could wrap it in a def:
>
> def(String x, Integer y) {
> statements
> }
Thats a nice syntax for anonymous functions. Given that we've full
closures, I'm not sure if we need anonymous functions / lambda functions
- but if we do need them, this is pretty nice syntax.
> Would this distinction between a block and a closure
> be confusing to people?
I'm not sure I've a great definition for the difference either :). I
tend to think of a closure as a block which may have explicit parameter
declarations and which is passed into a method, returned from a method
or assigned to a variable/parameter.
James
RSS Feed