Reputation: 520
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
Upvotes: 1
Views: 952
Reputation: 171144
You could also try changing the delegate of the returned Closure:
value = 5
Closure clos = A.doSomethingWith
// Set the closure delegate
clos.delegate = [ value: value ]
clos(6) // Got 6
clos() // Got 5
Upvotes: 2
Reputation: 14539
I managed to do what you want by checking for unresolved properties in the script binding:
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"
Upvotes: 1