用于模拟“继续”的最佳模式在Groovy闭包 [英] Best pattern for simulating "continue" in Groovy closure
问题描述
看起来Groovy不支持break并从一个闭包内继续。什么是模拟这个的最好方法?
revs.eachLine {line - >
if(line ==〜/ - {28} /){
//继续下一行...
}
}
您只能支持继续干净,特别是像每个线路和每个东西。无法支持断点与如何评估这些方法有关,没有考虑没有完成可以传递给该方法的循环。以下是如何支持continue -
最佳方法(假设您不需要生成的值)。
revs.eachLine {line - >
if(line ==〜/ - {28} /){
return //从闭包返回
}
}
如果你的示例真的很简单,这对于可读性是有好处的。
revs.eachLine {line - >
if(!(line ==〜/ - {28} /)){
//做你通常做的事
}
}
另一个选项,模拟继续在字节码级别通常执行的操作。
revs.eachLine {line - >
while(true){
if(line ==〜/ - {28} /){
break
}
//正常代码的剩余
break
}
}
break是通过异常:
try {
revs.eachLine {line - >
if(line ==〜/ - {28} /){
throw new Exception(Break)
}
}
} catch(Exception e) {} //只是删除异常
您可能希望使用自定义异常类型,真正的异常,特别是如果你在该类中有其他可能抛出真正异常的处理,如NumberFormatExceptions或IOExceptions。
It seems that Groovy does not support break and continue from within a closure. What is the best way to simulate this?
revs.eachLine { line -> if (line ==~ /-{28}/) { // continue to next line... } }
解决方案You can only support continue cleanly, not break. Especially with stuff like eachLine and each. The inability to support break has to do with how those methods are evaluated, there is no consideration taken for not finishing the loop that can be communicated to the method. Here's how to support continue --
Best approach (assuming you don't need the resulting value).
revs.eachLine { line -> if (line ==~ /-{28}/) { return // returns from the closure } }
If your sample really is that simple, this is good for readability.
revs.eachLine { line -> if (!(line ==~ /-{28}/)) { // do what you would normally do } }
another option, simulates what a continue would normally do at a bytecode level.
revs.eachLine { line -> while (true) { if (line ==~ /-{28}/) { break } // rest of normal code break } }
One possible way to support break is via exceptions:
try { revs.eachLine { line -> if (line ==~ /-{28}/) { throw new Exception("Break") } } } catch (Exception e) { } // just drop the exception
You may want to use a custom exception type to avoid masking other real exceptions, especially if you have other processing going on in that class that could throw real exceptions, like NumberFormatExceptions or IOExceptions.
这篇关于用于模拟“继续”的最佳模式在Groovy闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!