Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generically implementing a Java Single-Abstract-Method interface with a Scala closure?

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")
}
like image 296
Duncan McGregor Avatar asked Jun 26 '11 09:06

Duncan McGregor


4 Answers

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.

like image 165
retronym Avatar answered Nov 04 '22 02:11

retronym


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.

like image 41
paradigmatic Avatar answered Nov 04 '22 01:11

paradigmatic


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.

like image 24
IttayD Avatar answered Nov 04 '22 03:11

IttayD


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...

like image 21
Kim Stebel Avatar answered Nov 04 '22 02:11

Kim Stebel