0

我在玩 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)

}
4

1 回答 1

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]]
于 2013-10-02T22:19:09.177 回答