优雅的方式做...而在groovy

ejk8hzay  于 7个月前  发布在  其他
关注(0)|答案(7)|浏览(77)

如何在groovy中编写这样的代码?

do {

  x.doIt()

} while (!x.isFinished())

字符串
因为groovy中没有do ... while语法。

还没有'do... while()'语法。

由于不明确,我们还没有向Groovy添加对do.. while的支持
参考文献:

eh57zj3b

eh57zj3b1#

你可以滚动你自己的循环,这几乎是你想要的。这里有一个loop { code } until { condition }的例子你不能有一个对应的loop { code } while { condition },因为while是一个关键字。但是你可以叫它别的东西。
不管怎样,这里有一些粗略的until循环的代码。一个问题是你需要为until条件使用大括号来使它成为一个闭包。它可能有其他问题。

class Looper {
   private Closure code

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

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

字符串
使用方法:

import static Looper.*

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

deyfvvtc

deyfvvtc2#

这是最接近Groovy中纯粹基于语言语法的 do-while

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

字符串
花括号内(闭包内)的最后一条语句被计算为循环退出条件。
除了continue关键字之外,还可以使用一个扩展名。
另外一个好处是,循环可以参数化(有点),比如:

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


然后在其他地方:

while (somethingToDo(x)) continue


以前我在这里提出了这个答案:如果没有do-while语句,我如何使用Groovy遍历inputStream中的所有字节?

ttp71kqs

ttp71kqs3#

根据您的使用情况,有如下选项:do .. while() in Groovy with inputStream?
或者你可以这样做:

x.doIt()
while( !x.finished ) { x.doIt() }

字符串

while( true ) {
    x.doIt()
    if( x.finished ) break
}

0h4hbjxa

0h4hbjxa4#

你可以在常规的while循环中使用一个条件变量:

def keepGoing = true
while( keepGoing ){
    doSomething()
    keepGoing = ... // evaluate the loop condition here
}

字符串

3gtaxfhh

3gtaxfhh5#

更新Groovy 2.6已经被放弃,专注于3.0。

从Groovy 2.6开始,在启用新的Parrot Parser时支持do-while,从Groovy 3.0开始,这是默认值。参见release notes

// classic Java-style do..while loop
def count = 5
def fact = 1
do {
    fact *= count--
} while(count > 1)
assert fact == 120

字符串

zlwx9yxi

zlwx9yxi6#

现在,Groovy已经支持do/while

do {

  x.doIt()

} while (!x.isFinished())

字符串

ui7jx7zq

ui7jx7zq7#

或者你可以用Groovier的方式实现它:

def loop(Closure g){
    def valueHolder = [:]
    g.delegate = valueHolder
    g.resolveStrategy = Closure.DELEGATE_FIRST
    g()
    [until:{Closure w ->
        w.delegate = valueHolder
        w.resolveStrategy = Closure.DELEGATE_FIRST
        while(!w()){
        g()
        }
        }]
}

字符串

相关问题