是否有可能在 groovy 中打破闭包 [英] is it possible to break out of closure in groovy

查看:16
本文介绍了是否有可能在 groovy 中打破闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法打破"常规的闭包.

is there a way to 'break' out of a groovy closure.

可能是这样的:

[1, 2, 3].each { 
  println(it)
  if (it == 2)
    break 
}

推荐答案

你可以抛出异常:

try {
    [1, 2, 3].each { 
        println(it)
        if (it == 2)
            throw new Exception("return from closure") 
    }
} catch (Exception e) { }

Use 也可以使用findAll"或grep"来过滤您的列表,然后使用each".

Use could also use "findAll" or "grep" to filter out your list and then use "each".

[1, 2, 3].findAll{ it < 3 }.each{ println it }

这篇关于是否有可能在 groovy 中打破闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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