LANGUAGE/Java & Groovy 2016. 1. 24. 15:00

///// Groovy (그루비)

그루비는 정말 유연하다. 그리고 여러가지 클로저를 지원한다.


처음에 나는 그냥 적당히 each라는 클로저를 즐겨 사용하였다. 


그런데 each클로저안에서 빠져나오고 싶은 경우가 생겨서 방법을 찾아본 끝에


결론적으로 each를 애용 할 수 없게 되었다.




///// each

- each클로저에서 break명령은 없다.

- 하지만 try/catch를 이용하여 빠져나올 수 는 있다.


try {

    [1, 2, 3].each { 

        println it

        if (it == 2) new Exception("return from closure") 

    }

} catch (Exception e) { }




///// 대안 (find, any)

- each보다는 find나 any 등 다른 클로저를 사용하는 것이 현명해 보인다.

- 클로저 안에서 true를 반환하면 break와 동일효과를 갖는다.


[1, 2, 3].find { 

    println it                 // do the stuff that you wanted to before break

    if (it == 2) return true     // break

    return false              // keep looping

}






///// 참고

is it possible to break out of closure in groovy: 

http://stackoverflow.com/questions/1336704/is-it-possible-to-break-out-of-closure-in-groovy


Break from groovy each closure:

http://stackoverflow.com/questions/3049790/break-from-groovy-each-closure