繁体   English   中英

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

[英]Groovy equivalent for Scala implicit parameters - extended

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

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

我正在寻找一种方式来表达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时,失败发生在“编译器无法静态确定'value'可用”

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

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

value = 5

Closure clos = A.doSomethingWith

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

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

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

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