模拟“继续"的最佳模式在 Groovy 闭包中 [英] Best pattern for simulating "continue" in Groovy closure

查看:12
本文介绍了模拟“继续"的最佳模式在 Groovy 闭包中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎 Groovy 不支持闭包内的 breakcontinue.模拟这种情况的最佳方法是什么?

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...
    }
}

推荐答案

只能支持继续干净,不能中断.尤其是像 eachLine 和 each 这样的东西.无法支持中断与如何评估这些方法有关,没有考虑未完成可以与方法通信的循环.以下是如何支持继续 --

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
    }
}

另一个选项,模拟 continue 在字节码级别通常会做什么.

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

您可能希望使用自定义异常类型来避免屏蔽其他真正的异常,尤其是当您在该类中进行其他可能引发真正异常的处理时,例如 NumberFormatExceptions 或 IOExceptions.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆