我正在玩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)
}
答案 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]]