Programming

Groovy "각"폐쇄에서 벗어날 수 있습니까?

procodes 2020. 6. 19. 21:43
반응형

Groovy "각"폐쇄에서 벗어날 수 있습니까?


breakGroovy에서 가능 .each{Closure}합니까, 아니면 클래식 루프를 사용해야합니까?


아니요, 예외를 발생시키지 않고 "각"을 중단 할 수는 없습니다. 특정 조건에서 중단을 중단하려면 클래식 루프가 필요할 수 있습니다.

또는 각각 대신 "find"클로저를 사용하고 휴식을 취했을 때 true를 반환 할 수 있습니다.

이 예제는 전체 목록을 처리하기 전에 중단됩니다.

def a = [1, 2, 3, 4, 5, 6, 7]

a.find { 
    if (it > 5) return true // break
    println it  // do the stuff that you wanted to before break
    return false // keep looping
}

인쇄물

1
2
3
4
5

6 또는 7을 인쇄하지 않습니다.

클로저를 받아들이는 커스텀 브레이크 동작으로 자신 만의 반복자 메서드를 작성하는 것도 정말 쉽습니다.

List.metaClass.eachUntilGreaterThanFive = { closure ->
    for ( value in delegate ) {
        if ( value  > 5 ) break
        closure(value)
    }
}

def a = [1, 2, 3, 4, 5, 6, 7]

a.eachUntilGreaterThanFive {
    println it
}

또한 인쇄합니다 :

1
2
3
4
5    

교체 을 가진 루프 어떤 폐쇄.

def list = [1, 2, 3, 4, 5]
list.any { element ->
    if (element == 2)
        return // continue

    println element

    if (element == 3)
        return true // break
}

산출

1
3

No, you can't break from a closure in Groovy without throwing an exception. Also, you shouldn't use exceptions for control flow.

If you find yourself wanting to break out of a closure you should probably first think about why you want to do this and not how to do it. The first thing to consider could be the substitution of the closure in question with one of Groovy's (conceptual) higher order functions. The following example:

for ( i in 1..10) { if (i < 5) println i; else return}

becomes

(1..10).each{if (it < 5) println it}

becomes

(1..10).findAll{it < 5}.each{println it} 

which also helps clarity. It states the intent of your code much better.

The potential drawback in the shown examples is that iteration only stops early in the first example. If you have performance considerations you might want to stop it right then and there.

However, for most use cases that involve iterations you can usually resort to one of Groovy's find, grep, collect, inject, etc. methods. They usually take some "configuration" and then "know" how to do the iteration for you, so that you can actually avoid imperative looping wherever possible.


Just using special Closure

// declare and implement:
def eachWithBreak = { list, Closure c ->
  boolean bBreak = false
  list.each() { it ->
     if (bBreak) return
     bBreak = c(it)
  }
}

def list = [1,2,3,4,5,6]
eachWithBreak list, { it ->
  if (it > 3) return true // break 'eachWithBreak'
  println it
  return false // next it
}

(1..10).each{

if (it < 5)

println it

else

return false


You could break by RETURN. For example

  def a = [1, 2, 3, 4, 5, 6, 7]
  def ret = 0
  a.each {def n ->
    if (n > 5) {
      ret = n
      return ret
    }
  }

It works for me!

참고URL : https://stackoverflow.com/questions/3049790/can-you-break-from-a-groovy-each-closure

반응형