Matroska
Matroska

Reputation: 6923

Scala syntactic sugar with java listener pattern

I have to use java code in my scala project. The java code encourages the usage of a listener pattern. The code is something like this:

 asyncHttpClient.prepareGet("http://www.ning.com/ ").execute(new AsyncCompletionHandler<Response>(){

    @Override
    public Response onCompleted(Response response) throws Exception{
        // Do something with the Response
        // ...
        return response;
    }

    @Override
    public void onThrowable(Throwable t){
        // Something wrong happened.
    }
});

I am wondering if it is possible to use anything better in scala with this code. I know there is a paper written by Martin Odersky saying that observer pattern is bad but I didn't go deep with the matter. Thanks

Upvotes: 4

Views: 907

Answers (2)

Aaron Novstrup
Aaron Novstrup

Reputation: 21017

If you can't change the signature of your execute method, you could write a convenience method to simplify creation of the callback:

def async(f: Response => Response)(handler: Throwable => Unit) =
   new AsyncCompletionHandler[Response]() {
      @throws(classOf[Exception])
      override def onCompleted(response: Response): Response = 
         f(response)

      override def onThrowable(t: Throwable) = handler(t)
   }

Then you can write your code like

 asyncHttpClient.prepareGet("http://www.ning.com/ ").execute(async {
    response => // do something with response
 } { 
    caught => // handle failure
 }

Upvotes: 3

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

import scala.actors.Futures.future
def asyncDiv(n: Int, d: Int) = future { try { Left(n / d) } catch { case ex => Right(ex) } }

Example:

scala> asyncDiv(5, 2)
res9: scala.actors.Future[Product with Serializable with Either[Int,java.lang.Throwable]] = <function0>

scala> res9()
res10: Product with Serializable with Either[Int,java.lang.Throwable] = Left(2)

scala> asyncDiv(3, 0)
res11: scala.actors.Future[Product with Serializable with Either[Int,java.lang.Throwable]] = <function0>

scala> res11()
res12: Product with Serializable with Either[Int,java.lang.Throwable] = Right(java.lang.ArithmeticException: / by zero)

Upvotes: 2

Related Questions