Elegant way for do ... while in groovy

MariuszS picture MariuszS · Jan 4, 2014 · Viewed 66.4k times · Source

How to do code something like this in groovy?

do {

  x.doIt()

} while (!x.isFinished())

Because there is no do ... while syntax in groovy.

No 'do ... while()' syntax as yet.

Due to ambiguity, we've not yet added support for do .. while to Groovy

References:

Answer

Steve Sowerby picture Steve Sowerby · Jan 4, 2014

You can roll your own looping that's almost what you want. Here's an example with loop { code } until { condition } You can't have a corresponding loop { code } while { condition } because while is a keyword. But you could call it something else.

Anyway here's some rough and ready code for loop until. One gotcha is you need to use braces for the until condition to make it a closure. There may well be other issues with it.

class Looper {
   private Closure code

   static Looper loop( Closure code ) {
      new Looper(code:code)
   }

   void until( Closure test ) {
      code()
      while (!test()) {
         code()
      }
   }
}

Usage:

import static Looper.*

int i = 0
loop {
   println("Looping : "  + i)
   i += 1
} until { i == 5 }