Pete Pete - 4 years ago 177
Scala Question

Scala: how to use a Java callback API

Assume you are using a 3rd party Java API which streams data, asynchronously, via a callback. What (fundamental) design options do we have if we use such an API in Scala? I am new to the language. Here's what I thought of:


  1. Provide a Scala function from the wild to use as the callback (for example create some
    object
    which contains the callback function)

  2. We can optionally have this object send a message to an Akka actor (pass the data along). It this way we can fuel an actor system with input data.

  3. Data packaging-- a case class... but remember the data originate from a Java function. Is our only option for the Scala callback to receive the raw data using multiple arguments (strings, ints, doubles) before packing in a case class instance?


Answer Source
  1. Provide a Scala function from the wild to use as the callback (for example create some object which contains the callback function)

Yes. You should use Scala 2.12, there the Scala Functions are compiled to Java SAMs and you can just stick them into the Java API.

  1. We can optionally have this object send a message to an Akka actor (pass the data along). It this way we can fuel an actor system with input data.

Yes, you could. That's not alternative to 1, it's something you would do within the function you mention in 1.

  1. Data packaging-- a case class... but remember the data originate from a Java function. Is our only option for the Scala callback to receive the raw data using multiple arguments (strings, ints, doubles) before packing in a case class instance?

Not sure I understand. You want to put in a function that expects a different type than what is provided? As in, your API expects a callback handler that takes 3 parameters, and instead you'd like to provide one that takes one, a case class? I have a feeling that's not going to work. I'd rather just instantiate the case class within the function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download