[groovy-user] Binding 'unbound' MethodClosures
I was trying out a rather obscure implementation of a Builder to simulate a fluent DSL and landed a somewhat odd problem. (that was a mouthful! :P)
Here's what I'm trying to do.
def method = List.&get
def first = method.curry(0)
def list = []
first.delegate = list
list << 'foo'
first() //=> 'foo'
It obviously works with...
def method = list.&get //NOTE the lowercase 'l'
... but as part of the DSL, I don't get to create an instance of the target object until after the method to be invoked has been determined.
The DSL looks somehing like this,
Will.add(item).to(cart).if(condition1, condition2, ...)
Will.remove(item).from(cart).if(condition1, condition2, ...)
I realize that I could just cache the method (as a string) and the 'item' and simply...
cart."$method"(item)
... but I thought it'd be really groovy if I could cache them as a curried MethodClosure (Cart.&add.curry(item)). Except MethodClosures with Class owners (List.&get), as opposed to instance owners (list.&get) don't seem to have a valid owner to target calls to. Plus, closures don't allow modiifcation of their owner or thisObject properties.
On a more general note, I think it's Groovy's cool, approachable syntax that allows us to create edge cases like this that really push the envelope. Keep that funky Groove goin' brotha's!
--
Saager Mhatre