# List builder in groovy

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)
if(condition2)
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?

-
Can you give an example of how it would work building a list? Found this on the Groovy Console from a year ago that mimics the yield method? –  tim_yates Jan 31 '13 at 14:52
The first example is actually a complete one and equivalent to the second: I'm just using the standard with closure with implicit use of the List.add instance method on the initial empty list. –  Stephen Swensen Jan 31 '13 at 15:54
I'm quite intrigued by the Groovy Console reference you gave me, I'll investigate! –  Stephen Swensen Jan 31 '13 at 15:56
I also wrote a package called groovy-stream which lets you compute a stream of objects on demand and lets you do stuff lazily like this. As an aside, I often use your with method 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 '13 at 16:02