Can you break from a Groovy “each” closure?

后端 未结 6 1187
不思量自难忘°
不思量自难忘° 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:43

    Nope, you can't abort an "each" without throwing an exception. You likely want a classic loop if you want the break to abort under a particular condition.

    Alternatively, you could use a "find" closure instead of an each and return true when you would have done a break.

    This example will abort before processing the whole list:

    def a = [1, 2, 3, 4, 5, 6, 7]
    
    a.find { 
        if (it > 5) return true // break
        println it  // do the stuff that you wanted to before break
        return false // keep looping
    }
    

    Prints

    1
    2
    3
    4
    5
    

    but doesn't print 6 or 7.

    It's also really easy to write your own iterator methods with custom break behavior that accept closures:

    List.metaClass.eachUntilGreaterThanFive = { closure ->
        for ( value in delegate ) {
            if ( value  > 5 ) break
            closure(value)
        }
    }
    
    def a = [1, 2, 3, 4, 5, 6, 7]
    
    a.eachUntilGreaterThanFive {
        println it
    }
    

    Also prints:

    1
    2
    3
    4
    5    
    

提交回复
热议问题