is it possible to break out of closure in groovy

后端 未结 9 1897
醉梦人生
醉梦人生 2020-12-09 08:33

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

maybe something like this:

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


        
9条回答
  •  萌比男神i
    2020-12-09 08:58

    You can throw an exception:

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

    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 }
    

提交回复
热议问题