...
| Code Block | ||
|---|---|---|
| ||
def value = [1, 2, 3].join('-')
assert value == '1-2-3'
|
Python이나 Ruby에서 yield 문을 통해 지원되던 스타일 또한 사용가능 합니다. 차이점은 yield 문이 아니라 클로저를 사용한다는 점입니다:
...
class Foo {
myGenerator(Closure yield) {
yield.call("A")
yield.call("B")
yield.call("C")
}
static void main(args) {
def foo = new Foo()
for (x in foo.myGenerator) {
println x
}
}
}
def foo = new Foo()
for (x in foo.myGenerator) {
print("${x}-")
}
위 코드의 출력은 다음과 같습니다:
A-B-C-
메서드 선언부에 쓴 "Closure"는 생략 가능합니다. 클로저 호출을 마치 메서드 호출처럼 쓸 수 있게 해주는 문법적 장치(syntax sugar)가 있다면 Groovy 제너래이터가 더 Python/Ruby에 가깝게 보일 것입니다. 특히 괄호 또한 생략 가능하기 때문에 아래와 같이 호출할 수 있습니다:
...
class Foo {
myGenerator(yield) {
yield "A"
yield "B"
yield("C")
}
static void main(args) {
def foo = new Foo()
foo.myGenerator { println "Called with ${it}" }
}
}