我必须在我的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
}