Groovy - how to exit each loop?

前端 未结 4 1695
粉色の甜心
粉色の甜心 2021-02-03 21:39

I\'m new to Grails/Groovy and am trying to find a node in a an xml file; I\'ve figured out how to iterate over all of them, but I want to exit the loop when the target node is f

4条回答
  •  不要未来只要你来
    2021-02-03 22:34

    Regarding breaking out of the each loop see: is it possible to 'break' out of a groovy closure

    Basically you have to throw and exception and catch it. The "break" keyword is only allowed inside loops not iterated "closures" (really code blocks).

    You can use any complex code with "find" just make sure the function you call returns a Boolean. For example:

    Boolean test(val) {
        println "Testing $val"
        return val == 1
    }
    
    def found = [3,4,5,1,6,3].find { test(it) }
    
    println "Found $found"

提交回复
热议问题