0

I was playing with scala (newbie) and I was trying to use Java 7 NIO (because I like to start easy). But I can't work out how to instantiate the CompletionHandler for the accept. The following code is wrong and I can't fix it:

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)

}
Shadowlands
  • 14,994
  • 4
  • 45
  • 43
gotch4
  • 13,093
  • 29
  • 107
  • 170

1 Answers1

2

In order to create the connectHandler instance, you need to implement the CompletionHandler methods:

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

And, because the interface type is invariant in A, but the method you're calling is contravariant in A:

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

you need to cast to make the types check:

socketServer accept(1, connectionHandler.asInstanceOf[CompletionHandler[java.nio.channels.AsynchronousSocketChannel, _ >: Any]]
yakshaver
  • 2,472
  • 1
  • 18
  • 21