I'm a big fan of yield return found in C# and computation expressions found in F#. That is, language features which allow you to build streams of objects which are computed on demand (state-machines or monads under the covers).
As far as I know, there is no such feature in Groovy. However, I thought the following idea for a "list builder" of sorts might give me some of the benefits I seek (discouraging mutation; favoring expressions over statements):
def list = [].with {
if(condition1)
add 'x'
if(condition2)
add 'y'
it
}
vs. the more traditional declare an empty list and mutate it like so:
def list = []
if(condition1)
list << 'x'
if(condition2)
list << 'y'
I'm interested to know how the Groovy community in general might react to my "list builder". Is it non-idiomatic and to be avoided? Or is it a worthy solution to a worthy cause?
yieldmethod? – tim_yates Jan 31 at 14:52withclosure with implicit use of theList.addinstance method on the initial empty list. – Stephen Swensen Jan 31 at 15:54withmethod as it feels "cleaner" than the mutating example in your second snippet (and doesn't give you loads of named local variables hanging around out of context), but I'm never sure if the benefit goes beyond my taste ;-) – tim_yates Jan 31 at 16:02