如何在Scala中实例化Java 7完成处理程序

时间:2013-10-02 21:49:39

标签: scala nio2

我正在玩scala(新手),我正在尝试使用Java 7 NIO(因为我喜欢开始轻松)。但我无法弄清楚如何为接受实例化CompletionHandler。以下代码是错误的,我无法解决它:

package async

import java.nio.channels.AsynchronousServerSocketChannel
import java.net.InetAddress
import java.net.InetSocketAddress
import java.nio.channels.CompletionHandler
import java.nio.channels.AsynchronousSocketChannel

class AsyncServer (port: Int) {

  val socketServer = AsynchronousServerSocketChannel.open();
  socketServer.bind(new InetSocketAddress(port))

  val connectionHandler = new CompletionHandler[AsynchronousSocketChannel, Integer](){

  }

  def init() = socketServer accept(1 ,  connectionHandler)

}

1 个答案:

答案 0 :(得分:2)

要创建connectHandler实例,您需要实现CompletionHandler方法:

...
val connectionHandler = new CompletionHandler[AsynchronousSocketChannel, Integer] {
  def completed(result: AsynchronousSocketChannel, attachment: Integer ) {}
  def failed(exc: Throwable , attachment: Integer) {}
}
...

并且,因为A中的接口类型是不变的,但是你在A中调用的方法是逆变的:

...
public abstract <A> void accept(A attachment,
                                CompletionHandler<AsynchronousSocketChannel,? super A> handler);
...

你需要强制转换才能进行类型检查:

socketServer accept(1, connectionHandler.asInstanceOf[CompletionHandler[java.nio.channels.AsynchronousSocketChannel, _ >: Any]]