具有 Java 侦听器模式的 Scala 语法糖
我必须在我的 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 写了一篇论文说观察者模式很糟糕,但我没有深入探讨这个问题。 谢谢
I have to use java code in my scala project. The java code encourages the usage of a listener pattern. The code is 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 in scala with this code. I know there is a paper written by Martin Odersky saying that observer pattern is bad but I didn't go deep with the matter.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您无法更改
execute
方法的签名,您可以编写一个方便的方法来简化回调的创建:然后您可以编写如下代码
If you can't change the signature of your
execute
method, you could write a convenience method to simplify creation of the callback:Then you can write your code like
例子:
Example: