groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Jochen Theodorou" <>
Subject Aw: "External" closures, why?
Date Tue, 01 Dec 2015 16:44:33 GMT
The syntax is not new, Groovy had this kind of "attached block" since pre Groovy 1.0 times.


def foo(c) {c()}
assert foo {1} == 1

def bar(shouldCall, toBeCalled) {
  if (shouldCall) return toBeCalled() else return null
} // the returns are actually optional
assert bar(true) {1} == 1
assert bar(true, {1}) == 1 //alternative syntax
assert bar(false) {1} == nulll
assert bar(false, {1}) == nulll //alternative syntax

This kind of block usage w
As for the semantics... The type conversion was done to align Groovy with JDK8 lambda expressions
a bit. Lambda expressions in Java are a bit what groovy.lang.Closure is used for in Groovy,
of course with more limitations for Java.... but while we depend on a single type and use
meta information to know how many parameters this has and what types they declare for their
usage, the Java solution was to not have a base class for lambdas. Instead the lambda is converted
at runtime (it is a method in the declaring class plus a dynamic proxy to call that method
using invokedynamic) to a SAM type. SAM means "single abstract method" and in Java specifically
an interface with a single abstract method (static and default methods are not counted in
here of course). 

bye Jcohen

> Gesendet: Dienstag, 01. Dezember 2015 um 17:18 Uhr
> Von: alessio <>
> An:
> Betreff: "External" closures, why?
> Hi,
> I have just started to dig into Groovy and have been mostly impressed
> by what it offers, however when I had a look at handling database
> calls (
> I stumbled upon a rather weird syntax
>   sql.eachRow('select * from PROJECT where name=:foo', [foo:'Gradle']) {
>        // process row
>    }
> Usually I'd say this is a "regular" block scope but in this context it
> was obviously a closure/function pointer/callback. It took me a while
> to dig into this to find out that it can also be passed as second
> argument to the method and was added in 2.2
> (the JSR link does
> not work anymore)
> My question now is, why? Apparently pre-2.2 one had to cast the
> closure to the appropriate type. But why making it possible to
> actually define the closure outside of the respective call?
> At least for me this is HIGHLY confusing.
> Thanks

View raw message