[英]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.