Scala隐式参数的Groovy等价物 - 扩展

时间:2012-11-14 14:17:46

标签: scala groovy closures implicits

此问题延伸了我之前的Groovy equivalent for Scala implicit parameters

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

我正在寻找一种方式来表达这样的事情:

// 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时,失败发生为“编译器无法静态确定'value'可用”

那么,有没有人建议这种情况?干杯

2 个答案:

答案 0 :(得分:2)

您也可以尝试更改返回的Closure的委托:

value = 5

Closure clos = A.doSomethingWith

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

clos(6)  // Got 6
clos()   // Got 5

答案 1 :(得分: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"