Groovy - how to exit each loop?

前端 未结 4 1650
粉色の甜心
粉色の甜心 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:35

    You cannot do it elegantly. You might see some people suggest throwing an Exception, but that's just plain ugly.

    Here's some mailing list discussion on using each vs. for, and a couple people say that for is preferred because of each's inability to break from the iteration.

    Your best bet is probably to change over to a for loop and iterate:

    for(def domain : records.children()) { // this may need some tweaking depending on types
        // do stuff
        if(condition) {
            break;
        }
    }
    

    Either that, or like you said, maybe use find or findAll to find the element you're looking for (the following code is paraphrased, I don't have time yet to test it out):

    def result = records.children().find { domain -> domain.@domain_name == targetDomain }
    result.children().each {
        // print stuff
    }
    

    Related SO questions:

    • best-pattern-for-simulating-continue-in-groovy-closure
    • is-it-possible-to-break-out-of-closure-in-groovy

提交回复
热议问题