1
我尝试实施循环和无限循环检查,因此,如果周期执行超过CONST
时候,它会抛出异常:如何实现类似的功能,而周期
val MAX_CYCLES = 1000000
@throws(classOf[InfinityLoopException])
def guardedWhile(condition:() => Boolean)(body:() => Unit): Unit = {
var cnt = 0
while (condition.apply()) {
body.apply()
if (cnt > MAX_CYCLES) throw new InfinityLoopException()
cnt += 1
}
}
class InfinityLoopException() extends RuntimeException("Loop executed " + MAX_CYCLES + " cycles")
它的工作原理,但我希望有非函数签名像经典的同时:
var i = 0
guardedWhile(i < 5){
println(i)
}
现在我有:
var i = 0
guardedWhile(() => i < 5)(() => {
println(i)
i += 1
})