is it possible to break out of closure in groovy

后端 未结 9 1891
醉梦人生
醉梦人生 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条回答
  • 2020-12-09 09:02

    Take a look at Best pattern for simulating continue in groovy closure for an extensive discussion.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • Just using special Closure

    // declare and implement:
    def eachWithBreak = { list, Closure c ->
      boolean bBreak = false
      list.each() { it ->
         if (bBreak) return
         bBreak = c(it)
      }
    }
    
    def list = [1,2,3,4,5,6]
    eachWithBreak list, { it ->
      if (it > 3) return true // break 'eachWithBreak'
      println it
      return false // next it
    }
    
    0 讨论(0)
提交回复
热议问题