斯卡拉语法糖与java听众模式

时间:2011-02-11 00:31:48

标签: java scala listener pojo

我必须在我的scala项目中使用java代码。 java代码鼓励使用监听器模式。代码是这样的:

 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.
    }
});

我想知道是否可以使用此代码在scala中使用更好的内容。我知道Martin Odersky写的一篇论文说观察者模式很糟糕,但我没有深入研究这个问题。 感谢

2 个答案:

答案 0 :(得分:3)

如果您无法更改execute方法的签名,您可以编写一个简便方法来简化回调的创建:

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)
   }

然后你可以编写像

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

答案 1 :(得分:2)

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

示例:

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)