Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 {
      add 'x'
      add 'y'

vs. the more traditional declare an empty list and mutate it like so:

def list = []
  list << 'x'
  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?

share|improve this question
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.