简体   繁体   English

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

[英]Groovy equivalent for Scala implicit parameters - extended

This question extends my previous one Groovy equivalent for Scala implicit parameters 这个问题扩展了我之前的一个Groovy等效的Scala隐式参数

Not sure if this is the right way to develop from a previous topic, but anyway.. 不确定这是否是从前一个主题开发的正确方法,但无论如何..

I am looking for a way to express in groovy something like this: 我正在寻找一种方式来表达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

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. 由于scala中的含义,我似乎能够控制这种情况。 I am trying to find a way to do something similar in groovy. 我试图找到一种在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 */

Now, I went through the groovy closure definition at http://groovy.codehaus.org/Closures+-+Formal+Definition 现在,我在http://groovy.codehaus.org/Closures+-+Formal+Definition中查看了groovy闭包定义。

As I understand it, when the getter is called, the failure happens as "the compiler cannot statically determine that 'value' is available" 据我所知,当调用getter时,失败发生在“编译器无法静态确定'value'可用”

So, has anyone a suggestion for this scenario? 那么,有没有人建议这种情况? Cheers 干杯

You could also try changing the delegate of the returned Closure: 您还可以尝试更改返回的Closure的委托:

value = 5

Closure clos = A.doSomethingWith

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

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

I managed to do what you want by checking for unresolved properties in the script binding: 我通过在脚本绑定中检查未解析的属性来设法做你想要的事情:

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM