In our projects, we have style checks that suggest "for (x in y) ..." over "for
(T x : y) ...". The "in" form is groovy idiom and the ":" form is for java
compat. Switching to use "y.each { x-> ... }" or "y.forEach(x -> ...)" is a
personal preference. Note: the debugger steps through the for loop much more
easily.
Regarding the proposal to support return from enclosing within closure (or
lambda), there is a lot to consider. If closure is nested within another
closure, is the idea to only support return from the outermost scope (method)?
Re-writing as try/catch might prove expensive. That is not to say it could not
be done.
You could experiemnt with Groovy Macro to replace any "expr.each { ... }" with
some other expression. This can typically be done more quickly than an AST
transform. It may not be the final form of your solution, but does let you try
things quickly.
________________________________
From: OCsite <[email protected]>
Sent: Wednesday, December 4, 2024 11:03 AM
To: [email protected] <[email protected]>
Subject: [EXT] for loops, returns, and other animals
External Email: Use caution with links and attachments.
MG,
On 4. 12. 2024, at 16:11, MG <[email protected]> wrote:
* e.g. using a for(foo : foos) { ... } loop instead of canonical Groovy
foos.each { foo -> ... }, to be able to easily return from the for body from
multiple places using return statements.
For one, I would argue that the native and groovier (since more logical and
intuitive and intention-revealing for anyone who can read English completely
regardless whether he knows Java or not) variant should be the for/in loop,
like for (foo in foos). That weird and unintuitive colon thing should, in my
personal opinion, remain limited to code copy/pasted from Java (exactly like
var :))
That would not be worth an extra email though. I wonder, would it be perhaps
worth the effort to extend the language by adding a support for
method-returning from a closure?
A trivial (and most probably very very wrong and problems-inducing!) approach
might perhaps be an ASTT which would convert code like
def foo() {
bar.each { if (it) methodreturn it }
}
to something like
def foo() {
try {
bar.each { if (it) throw new MethodReturnException(value:it) }
} catch (MethodReturnException e) {
return e.value
}
}
Would it be perhaps worth the effort to add such an ASTT to Groovy? Not sure at
all... but it might help (a) to stick with the canonical foo.each instead of
enforcing for/ins, (b) also, in many cases like foo.find, foo.allResults, et
cetera, which are even more ugly to replace with plain ole loops.
All the best,
OC