How does one return from a groovy closure and stop its execution?

前端 未结 6 2104
难免孤独
难免孤独 2020-12-30 19:22

I would like to return from a closure, like one would if using a break statement in a loop.

For example:

largeListOfElements.each{ element->
             


        
6条回答
  •  轮回少年
    2020-12-30 20:13

    I think you want to use find instead of each (at least for the specified example). Closures don't directly support break.

    Under the covers, groovy doesn't actually use a closure either for find, it uses a for loop.

    Alternatively, you could write your own enhanced version of find/each iterator that takes a conditional test closure, and another closure to call if a match is found, having it break if a match is met.

    Here's an example:

    Object.metaClass.eachBreak = { ifClosure, workClosure ->
        for (Iterator iter = delegate.iterator(); iter.hasNext();) {
            def value = iter.next()
            if (ifClosure.call(value)) {
                workClosure.call(value)
                break
            }        
        }
    }
    
    def a = ["foo", "bar", "baz", "qux"]
    
    a.eachBreak( { it.startsWith("b") } ) {
        println "working on $it"
    }
    
    // prints "working on bar"
    

提交回复
热议问题