I'd like to port a little piece of code from Ruby to Groovy, and I'm stuck at this:
def given(array,closure) {
closure.delegate = array
closure()
}
given([1,2,3,4]) {
findAll { it > 4}
}
Right now it dies with this message:
Exception thrown: Cannot compare ConsoleScript0$_run_closure1 with value 'ConsoleScript0$_run_closure1@1e6743e' and java.lang.Integer with value '4'
.
I tried to set the closure's delegate to be the array, but it seems that in the findAll
method, it represents a closure, instead of an actual item from the array. I also tried to run the closure like this:
array.with {
closure(array)
}
but I still wasn't able to make it work. Any thoughts on what could work? Ruby's equivalent would be to instance_eval
the closure in the array's context.
EDIT: Running Mykola's code produced this output:
given [1, 2, 3, 4]
class Demo$_main_closure1
2
Exception thrown: Cannot compare Demo$_main_closure1 with value 'Demo$_main_closure1@fe53cf' and java.lang.Integer with value '2'
groovy.lang.GroovyRuntimeException: Cannot compare Demo$_main_closure1 with value 'Demo$_main_closure1@fe53cf' 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)
I'm running Groovy 1.6.5.