Elegant way for do … while in groovy

前端 未结 6 747
Happy的楠姐
Happy的楠姐 2020-12-29 00:44

How to do code something like this in groovy?

do {

  x.doIt()

} while (!x.isFinished())

Because there is no do ... w

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 01:18

    So many answers and not a single one without a redundant call, a shame ;)

    This is the closest it can get to purely language syntax based do-while in Groovy:

    while ({
        x.doIt()
        !x.isFinished()
    }()) continue
    

    The last statement within curly braces (within closure) is evaluated as a loop exit condition.

    Instead of continue keyword a semicolon can be used.

    Additional nice thing about it, loop can be parametrized (kind of), like:

    Closure somethingToDo = { foo ->
        foo.doIt()
        !foo.isFinished()
    }
    

    and then elsewhere:

    while (somethingToDo(x)) continue
    

    Formerly I've proposed this answer over here: How do I iterate over all bytes in an inputStream using Groovy, given that it lacks a do-while statement?

提交回复
热议问题