This question extends my previous one Groovy equivalent for Scala implicit parameters
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:
// 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. I am trying to find a way to do something similar in 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
As I understand it, when the getter is called, the failure happens as "the compiler cannot statically determine that 'value' is available"
So, has anyone a suggestion for this scenario? Cheers