如何使用()方法将参数传递给groovy
我希望在某个脚本的上下文中调用外部提供的闭包,但我希望它能够访问一个对象,该对象的作用域是从中调用闭包的方法:如何使用()方法将参数传递给groovy,groovy,Groovy,我希望在某个脚本的上下文中调用外部提供的闭包,但我希望它能够访问一个对象,该对象的作用域是从中调用闭包的方法: def method1(Map config) { ... with config.some_closure //here I'd like to pass the config map as a param. } //now invoke: method1 { some_value: 1, some_closure: { def param1 ->
def method1(Map config) {
...
with config.some_closure //here I'd like to pass the config map as a param.
}
//now invoke:
method1 {
some_value: 1,
some_closure: { def param1 ->
//access param here, eg:
param1.some_value = 2
}
}
我当前的解决方法是将我的对象分配给脚本范围的变量,以便提供的闭包可以访问它:
globalConfig = null
def method1(Map config) {
globalConfig = config
...
with config.some_closure //here I'd like to pass the config map as a param.
}
//now invoke:
method1 {
some_value: 1,
some_closure: {
//access global here, eg:
globalConfig.some_value = 2
}
}
有更好的方法吗?我认为使用委托是允许参数传递的with的有效替代方法:
def method1(Map config) {
...
config.some_closure.delegate = this // retain access to this object's methods
config.some_closure(config) //pass config explicitly
}
//now invoke:
method1 {
some_value: 1,
some_closure: { def param1 ->
//access param here, eg:
param1.some_value = 2
}
}
我认为咖喱是你想要的:
def method1(Map config) {
with config.some_closure.curry(config) // this is a new closure taking no arguments, where param1 has been fixed.
}
//now invoke:
method1 ([
some_value: 1,
some_closure: { def param1 ->
//access param here, eg:
param1.some_value = 2
}
])