4

我必须在我的 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 写的一篇论文说观察者模式很糟糕,但我没有深入探讨这个问题。谢谢

4

2 回答 2

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
 }
于 2011-02-11T02:34:18.440 回答
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)
于 2011-02-11T02:05:46.507 回答