Scala syntactic sugar with java listening pattern

I need to use java code in my scala project. Java code encourages the use of a listener pattern. The code looks 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 with scala with this code. I know that there is an article written by Martin Odersky, which says that the observer’s picture is bad, but I did not delve into this issue. Thanks

+4
source share
2 answers

If you cannot change the signature of your execute method, you can write a convenience method to make it easier to create a 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, for example

  asyncHttpClient.prepareGet("http://www.ning.com/ ").execute(async { response => // do something with response } { caught => // handle failure } 
+3
source
 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) 
+2
source

Source: https://habr.com/ru/post/1339286/


All Articles