我尝试使用无限循环检查实现while循环,因此如果循环执行超过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
})
答案 0 :(得分:3)
将参数更改为call-by-name。
def guardedWhile(condition: => Boolean)(body: => Unit): Unit = { ...
然后直接引用它们。
while (condition) {
body
. . .
按名称调用意味着每次引用它们时都会重新评估它们。