views:

316

answers:

3

There is an idiom in groovy to implement an Interface with a single closure. The closure must be prepared to handle whatever arguments are passed. That works fine. But how does one determine what method was called at the interface?

interface X
{ void f(); void g(int n); void h(String s, int n); }

x = {Object[] args -> println "method called with $args"} as X
x.f()

The args are available but that name of the method that was called is - apparently - not. Am I missing something?

A: 

You can use the dynamic MethodMissing Feature like shown in this Excample http://groovy.codehaus.org/Using+methodMissing+and+propertyMissing

With this you can implement a fallback method which can handle the calls to the interface methodes.

HaBaLeS
A: 

That feature is intended to be used for the common case of single-method interfaces like Comparable or Runnable (which are in Java often used as a substitute for closures).

Michael Borgwardt
+1  A: 

I think Michael Borgwardt is essentially right. The implementation you provide via the curly bracket syntax provides one method implementation that is used for ALL interface definitions:

interface X { void f(); void g(int n); void h(String s, int n); }
x = {Object[] args -> println "method called with $args"} as X

x.f()
x.g(5)
x.h("a string",2)

If you want to make a closure with a method implementation per method, use this alternate syntax:

interface X
{ void f(); void g(int n); void h(String s, int n); }

x = [
        f: {println "f is called"},
        g: {int i-> println "g is called with param ${i}"},
        h: {Object[] args -> println "h is called with ${args}"}
] as X

x.f()
x.g(5)
x.h("a string",2)

See the following for more information:

dsummersl