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

前端 未结 6 2102
难免孤独
难免孤独 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:21

    After paulmurray's answer I wasn't sure myself what would happen with an Exception thrown from within a closure, so I whipped up a JUnit Test Case that is easy to think about:

    class TestCaseForThrowingExceptionFromInsideClosure {
    
        @Test
        void testEearlyReturnViaException() {
            try {
                [ 'a', 'b', 'c', 'd' ].each {                 
                    System.out.println(it)
                    if (it == 'c') {
                        throw new Exception("Found c")
                    } 
                }
            }
            catch (Exception exe) {
                System.out.println(exe.message)
            }
        }
    }  
    

    The output of the above is:

    a
    b
    c
    Found c
    

    But remember that "one should NOT use Exceptions for flow control", see in particular this Stack Overflow question: Why not use exceptions as regular flow of control?

    So the above solution is less than ideal in any case. Just use:

    class TestCaseForThrowingExceptionFromInsideClosure {
    
        @Test
        void testEarlyReturnViaFind() {
            def curSolution
            [ 'a', 'b', 'c', 'd' ].find {                 
                System.out.println(it)
                curSolution = it
                return (it == 'c') // if true is returned, find() stops
            }
            System.out.println("Found ${curSolution}")
        }
    }  
    

    The output of the above is also:

    a
    b
    c
    Found c
    

提交回复
热议问题