这个问题扩展了我之前对 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 时,失败发生为“编译器无法静态确定‘值’可用”
那么,有人对这种情况有什么建议吗?干杯