Can you break from a Groovy “each” closure?

后端 未结 6 1146
不思量自难忘°
不思量自难忘° 2020-11-27 13:17

Is it possible to break from a Groovy .each{Closure}, or should I be using a classic loop instead?

6条回答
  •  温柔的废话
    2020-11-27 13:44

    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
    }
    

提交回复
热议问题