Can you break from a Groovy “each” closure?

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

    No, you can't break from a closure in Groovy without throwing an exception. Also, you shouldn't use exceptions for control flow.

    If you find yourself wanting to break out of a closure you should probably first think about why you want to do this and not how to do it. The first thing to consider could be the substitution of the closure in question with one of Groovy's (conceptual) higher order functions. The following example:

    for ( i in 1..10) { if (i < 5) println i; else return}
    

    becomes

    (1..10).each{if (it < 5) println it}
    

    becomes

    (1..10).findAll{it < 5}.each{println it} 
    

    which also helps clarity. It states the intent of your code much better.

    The potential drawback in the shown examples is that iteration only stops early in the first example. If you have performance considerations you might want to stop it right then and there.

    However, for most use cases that involve iterations you can usually resort to one of Groovy's find, grep, collect, inject, etc. methods. They usually take some "configuration" and then "know" how to do the iteration for you, so that you can actually avoid imperative looping wherever possible.

提交回复
热议问题