One annoyance I have when using Java libraries from Scala is the need to explicitly create an anonymous class every time we need to pass a callback function.

For example, if an object a provides the possibility to install a callback whenever it finishes doing something, usually this is implemented using an anonymous class with code similar to this:

a.onFinish(new OnFinishHandler {
  override def f(result: Result) {
    do_something_with_result
  }
})

This is a very awkward idiom to use in a language that support anonymous functions. This syntax would be much nicer if the library was written in Scala, the library author could implement this like:

a.onFinish { result => do_something_result }

Wouldn't it be nice if we could write this anyway? Turns out it's possible if we define an implicit conversion from Result => Any to OnFinishHandler:

object FuncToFinishHandlerConversion {
  implicit def funcToFinishHandlerConversion(callback: Result => Any): OnFinishHandler =  {
    new onFinishHandler() {
      override def f(result: Result): Unit = f(result)
    }
  }
}

Now if we import FuncToFinishHandlerConversion._ in the classes where we need to use a.onFinish, we just need to use:

a.onFinish { result => do_something_with_result }

We do need to define an implicit conversion for each type, but it pays off if we are using that external library a lot.



comments powered by Disqus