Created
March 23, 2012 08:48
-
-
Save purplefox/2168524 to your computer and use it in GitHub Desktop.
Groovy question
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
I have a method on a class which takes a Closure as an argument: | |
class Foo { | |
void register(Closure handler) | |
} | |
The closure represents a handler that will be called back some time in the future | |
In most cases users will specify the Closure directly when calling it: | |
new Foo().register { println "in handler" } | |
But there are other objects that can act as handlers and that I want to be able to pass to register too | |
E.g. I would like to do something like | |
class MyHandler implements Closure { | |
void call() { | |
println "in handler" | |
} | |
} | |
But this doesn't work since Closure is not interface. I've tried extending it too, and that doesn't seem to work. | |
Any ideas? | |
Tim, why not just require a particular method on objects that are handlers and not worry about whether they implement a particular interface or not? You could just require all handler classes to implement the call() method for example. Alternatively, why not have:
class Foo {
void register(handler) {
delegate.register(handler as Handler)
}
}
That would work if the handler
argument were a closure or an instance of Handler
.
Peter,
yup, makes sense.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, I was meaning java.util.concurrent.Callable but it is not applicable since handlers take an event as parameter.