As I understand it, when they finally come along, we will be able to substitute a Java closure for the equivalent single-method interface. Is there a standard Scala idiom for doing the same - implementing a Java Single Abstract Method interface with a Scala closure?
Ideally I'd like the following to automagically work
test("Closure") {
var event: PropertyChangeEvent = null
var label = new JLabel()
label.addPropertyChangeListener( {e: PropertyChangeEvent => event = e} )
label.setText("fred")
event.getNewValue should be ("fred")
}
There was a lengthy discussion about this in January.
http://www.scala-lang.org/node/8744
The idea was well received, and even taken a bit further than this proposal. But the devil is in the details, and a prototype implementation may yet find other problems with this proposal.
In scala, you can try implicit conversions:
implicit def func2PropertyChangeListener( f: ProperyChangeEvent => Unit ) =
new PropertyChangeListener {
def propertyChange( evt: PropertyChangeEvent ) = f(evt)
}
Then you just have to import the method and you can directly pass anonymous functions everywhere a PropertyChangeListener
is expected.
See http://www.tikalk.com/incubator/blog/simulating-sam-closures-scala
Use implicit conversion to add something like addSamListener
.
You'd need to write the conversion, but you wouldn't need to import it everywhere (just the one implicit conversion that adds addSamListener).
If all interface share the same method, you can use structural typing.
The only way to do this for every old Java interface is code generation. Since Java parsers are readily available and you only need to extract the interface name and method signature this should be fairly easy to do and it only needs to run once. In fact, it sounds like a good sunday evening project. Other people might benefit from it too...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With