groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <blackd...@gmx.org>
Subject Re: "External" closures, why?
Date Tue, 01 Dec 2015 22:30:55 GMT
Am 01.12.2015 um 20:56 schrieb alessio:
> On Tue, Dec 1, 2015 at 5:44 PM, Jochen Theodorou <blackdrag@gmx.org> wrote:
>> The syntax is not new, Groovy had this kind of "attached block" since pre Groovy
1.0 times.
>
> Alright, I did just run the code with against 2.0 (which was supposed
> not to support it) and it ran just fine.
 >
> But then, what does the documentation refer to when it says one can
> omit an explicit coercion as of 2.2?

example:

interface SamType{ int foo()}

def callFoo(SamType t) {t.foo()}
assert callFoo {1} == 1

this example would throw a MissingMethodException before Groovy 2.2, 
while this one here:

def callClosure(t) {t.call()}
assert callFoo {1} == 1

should work in any Groovy version. The difference here is that for this 
to work we can use any class being a parent to groovy.lang.Closure plus 
the class itself of course. In the case here I did not give a type, 
which is equal to using the base type of all types in Java and Groovy, 
which is java.lang.Object

>
>>
>> This kind of block usage w
>
> Something is missing here.

yes, sorry... some sleep and a proper email client ;)

[..]
> So far so good, the concept itself is not that much of a problem, the
> thing that I was simply wondering (and which confused the heck out of
> me :) ) is the choice to support mentioned form of passing the
> closure, which IMVHO could be utterly confusing, as the passed
> function is VISUALLY not part of the function call but "dangling"
> somewhere near it.

if you forget about lambdas and function pointers and such for a moment 
and simply think of a while loop:

while (x) { doSomething() }

then you will recognize this as perfectly in synch with the attached 
blocks I mentioned - of course only on the syntax level. On the semantic 
level there is a bit more than that.

And it so happens, that the most common usage of this syntaxis to 
provide a custom looping method to execute an action for each iteration:

list.each { println it }

This will iterate over all elements in the list and print them out.

bye Jochen

Mime
View raw message