Groovy等效于Scala隐式参数 - 扩展 [英] Groovy equivalent for Scala implicit parameters - extended
问题描述
此问题扩展了我之前的问题对于Scala隐式参数,Groovy等效
This question extends my previous one Groovy equivalent for Scala implicit parameters
不知道这是否是从上一个主题开发的正确方法,但无论如何..
Not sure if this is the right way to develop from a previous topic, but anyway..
寻找一种方式来表达在groovy这样的东西:
I am looking for a way to express in groovy something like this:
// 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中的隐含我似乎能够控制这种情况。
In general, I would like to execute a piece of logic, and have variables in it resolved based on the execution 'context'. With implicits in scala I seem to be able to control this scenario. I am trying to find a way to do something similar in groovy.
根据第一个问题的反馈,我试图这样来处理:
Based on the feedback from the first question I tried to approach it like this:
// 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闭包定义://groovy.codehaus.org/Closures+-+Formal+Definition
根据我的理解,当getter被调用时,失败发生为编译器不能静态地确定值可用
As I understand it, when the getter is called, the failure happens as "the compiler cannot statically determine that 'value' is available"
那么,有没有人对这种情况有建议?干杯
So, has anyone a suggestion for this scenario? Cheers
推荐答案
您也可以尝试更改返回的Closure的委托:
You could also try changing the delegate of the returned Closure:
value = 5
Closure clos = A.doSomethingWith
// Set the closure delegate
clos.delegate = [ value: value ]
clos(6) // Got 6
clos() // Got 5
这篇关于Groovy等效于Scala隐式参数 - 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!