is it possible to break out of closure in groovy

后端 未结 9 1922
醉梦人生
醉梦人生 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 09:03

    This is in support of John Wagenleiter's answer. Tigerizzy's answer is plain wrong. It can easily be disproved practically by executing his first code sample, or theoretically by reading Groovy documentation. A return returns a value (or null without an argument) from the current iteration, but does not stop the iteration. In a closure it behaves rather like continue.

    You won't be able to use inject without understanding this.

    There is no way to 'break the loop' except by throwing an exception. Using exceptions for this purpose is considered smelly. So, just as Wagenleiter suggests, the best practice is to filter out the elements you want to iterate over before launching each or one of its cousins.

提交回复
热议问题