如何使用groovy
编写类似这样的代码?
do {
x.doIt()
} while (!x.isFinished())
因为Groovy中没有do ... while
语法。
迄今为止还没有'do ... while()'语法。
由于存在歧义,我们尚未添加对Groovy的do ... while支持。
参考资料:
如何使用groovy
编写类似这样的代码?
do {
x.doIt()
} while (!x.isFinished())
因为Groovy中没有do ... while
语法。
迄今为止还没有'do ... while()'语法。
由于存在歧义,我们尚未添加对Groovy的do ... while支持。
参考资料:
你可以自己编写循环来满足你的需求。下面是一个使用loop { code } until { condition }
的示例。由于while是一个关键字,所以你无法使用对应的loop { code } while { condition }
。但你可以给它取别的名字。
无论如何,这里有一些简单粗暴的代码用于循环直到某个条件满足。唯一要注意的是,你需要使用大括号将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 }
while ({
x.doIt()
!x.isFinished()
}()) continue
continue
关键字。Closure<Boolean> somethingToDo = { foo ->
foo.doIt()
!foo.isFinished()
}
while (somethingToDo(x)) continue
根据你的使用情况,有如下选项:在Groovy中使用inputStream实现do .. while()循环
或者你可以这样做:
x.doIt()
while( !x.finished ) { x.doIt() }
或者
while( true ) {
x.doIt()
if( x.finished ) break
}
更新:Groovy 2.6已被放弃,集中精力开发3.0版本。
从Groovy 2.6开始,在启用新的Parrot解析器时支持do-while,而从Groovy 3.0开始,则是默认支持。请参见发行说明:
// classic Java-style do..while loop
def count = 5
def fact = 1
do {
fact *= count--
} while(count > 1)
assert fact == 120
您可以使用条件变量与常规 while 循环:
def keepGoing = true
while( keepGoing ){
doSomething()
keepGoing = ... // evaluate the loop condition here
}
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()
}
}]
}
loop({...}).until({...})
。因此,在loop()
的返回值上调用until()
。Groovy 命令表达式意味着您可以省略until()
前面的.
。 - Peter Ledbrook