2013-10-02 11 views
0

我正在玩scala(新手),並且正在嘗試使用Java 7 NIO(因爲我喜歡從容易開始)。但我無法解決如何實例化CompletionHandler接受。下面的代碼是錯誤的,我不能修復:我如何在Scala中實例化Java 7完成處理程序

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) 

} 

回答

2

爲了創建connectHandler情況下,你需要實現CompletionHandler方法:

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

而且,由於接口類型在不變A,但你調用方法是在逆變答:

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

你需要轉換爲使類型檢查:

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