두 손끝의 창조자

클로저가 마지막 파라미터일 때는 밖에서 넣을 수 있다 본문

패키지관리/Gradle

클로저가 마지막 파라미터일 때는 밖에서 넣을 수 있다

codinglog 2021. 12. 13. 17:13
import java.text.FieldPosition

def pos = configure(new FieldPosition(10)) {
    beginIndex = 1
    endIndex = 5
}
println pos.beginIndex
println pos.endIndex

Gradle 공홈에서 문서를 보고 있는데 위와 같은 구문이 있었다. 그런데 이 문법이 이해가 안 갔다.

configure 가 Prject 인터페이스의 메소드인건 알겠고, 파라미터로 FieldPosition 의 인스턴스를 넘기는 것도 알겠고.. 그런데 그 뒤에 있는 클로저는 뭐지..?

그루비는 클로저가 메서드의 마지막 인수인 경우, 외부에서 클로저를 넣을 수 있는 문법을 제공한다. 이딴건 왜 제공하는지 모르겠다. 사람 헷갈리게

그래서 위 구문은

import java.text.FieldPosition

def pos = configure(new FieldPosition(10), {
    beginIndex = 1
    endIndex = 5
})
println pos.beginIndex
println pos.endIndex

와 같다.

 

 

* 참조

Groovy Goodness: Passing Closures to Methods - Messages from mrhaki

 

Groovy Goodness: Passing Closures to Methods

A blog about Groovy, Clojure, Java and other cool developer subjects.

blog.mrhaki.com

Pass a closure (without comma or parens) as a last parameter of a function in Groovy - Stack Overflow

 

Pass a closure (without comma or parens) as a last parameter of a function in Groovy

How can I call the label function and set a closure to it as the last parameter in this way? This code works only if I call label with parentheses but I don't need them. Is it possible to set the c...

stackoverflow.com

 

반응형
Comments