我想端口一小段代碼從紅寶石到Groovy和我被困在此:我怎樣才能得到這個片段的工作?
def given(array,closure) {
closure.delegate = array
closure()
}
given([1,2,3,4]) {
findAll { it > 4}
}
現在死了此消息:
Exception thrown: Cannot compare ConsoleScript0$_run_closure1 with value '[email protected]' and java.lang.Integer with value '4'
。
我試圖將閉包的委託設置爲數組,但似乎在findAll
方法中,它表示閉包,而不是數組中的實際項目。我也試圖運行這樣的關閉:
array.with {
closure(array)
}
但我仍然無法使它的工作。有什麼想法可以工作? Ruby的等價物將是instance_eval
數組上下文中的閉包。
編輯:運行尼古拉的代碼生成的輸出:
given [1, 2, 3, 4]
class Demo$_main_closure1
2
Exception thrown: Cannot compare Demo$_main_closure1 with value '[email protected]' and java.lang.Integer with value '2'
groovy.lang.GroovyRuntimeException: Cannot compare Demo$_main_closure1 with value '[email protected]' and java.lang.Integer with value '2'
at Demo$_main_closure1_closure2.doCall(ConsoleScript3:15)
at Demo$_main_closure1.doCall(ConsoleScript3:15)
at Demo$_main_closure1.doCall(ConsoleScript3)
at Demo.given(ConsoleScript3:28)
at Demo$given.callStatic(Unknown Source)
at Demo.main(ConsoleScript3:12)
我跑的Groovy 1.6.5。
我已經更新了我的問題與輸出你的代碼。仍然不起作用。 – Geo 2009-11-15 18:58:46
是的。這就是我正在談論的。要麼我不明白'DELEGATE_ONLY'選項,或者1.6.5中存在錯誤。我明天將在工作中嘗試1.6.4。 – 2009-11-15 19:32:15
謝謝!請在有機會之後回覆。 – Geo 2009-11-15 19:50:02