簡體   English   中英

斯卡拉語法糖與java聽眾模式

[英]Scala syntactic sugar with java listener pattern

我必須在我的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寫的一篇論文說觀察者模式很糟糕,但我沒有深入研究這個問題。 謝謝

如果無法更改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
 }
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM