1

这个问题扩展了我之前对 Scala 隐式参数的 Groovy 等效项

不确定这是否是从以前的主题发展的正确方法,但无论如何..

我正在寻找一种用 groovy 表达的方式,如下所示:

// scala
object A {
    def doSomethingWith(implicit i:Int) = println ("Got "+i)
}
implicit var x = 5

A.doSomethingWith(6)  // Got 6
A.doSomethingWith     // Got 5

x = 0
A.doSomethingWith     // Got 0

一般来说,我想执行一段逻辑,并根据执行“上下文”解析其中的变量。使用 scala 中的隐式,我似乎能够控制这种情况。我正在尝试找到一种在 groovy 中做类似事情的方法。

根据第一个问题的反馈,我尝试这样处理:

// groovy
class A {
    static Closure getDoSomethingWith() {return { i = value -> println "Got $i" }} 
}

value = 5

A.doSomethingWith(6)  // Got 6
A.doSomethingWith()   /* breaks with
                         Caught: groovy.lang.MissingPropertyException: 
                         No such property: value for class: A */

现在,我在http://groovy.codehaus.org/Closures+-+Formal+Definition浏览了 groovy 闭包定义

据我了解,当调用 getter 时,失败发生为“编译器无法静态确定‘值’可用”

那么,有人对这种情况有什么建议吗?干杯

4

2 回答 2

2

您还可以尝试更改返回的闭包的委托:

value = 5

Closure clos = A.doSomethingWith

// Set the closure delegate
clos.delegate = [ value: value ]

clos(6)  // Got 6
clos()   // Got 5
于 2012-11-14T14:40:04.907 回答
1

我设法通过检查脚本绑定中未解析的属性来做你想做的事:

class A {
  static Closure getDoSomethingWith() { { i = value -> println "Got $i" } } 
}
A.metaClass.static.propertyMissing = { String prop -> binding[prop] }

value = 5


A.doSomethingWith 6  // Got 6
A.doSomethingWith() // prints "Got 5"
于 2012-11-14T14:31:11.777 回答