I am new to scala and am having an issue in calling a "generic" function in the java NIO library (from scala 2.10.x). Reducing the code to a simple test:
import java.net._
import java.nio.channels.{MembershipKey, DatagramChannel}
object Test {
val channel = DatagramChannel.open(StandardProtocolFamily.INET)
.setOption(StandardSocketOptions.SO_REUSEADDR, true)
...
}
This results in:
Error:(40, 48) type mismatch;
found : java.net.SocketOption[Boolean]
required: java.net.SocketOption[Any]
Note: Boolean <: Any, but Java-defined trait SocketOption is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true)
^
I assume there is some way to resolve this without resorting to writing a wrapper in java. Have tried recasting in a variety of ways without success.
Question: how do I resolve the above?
Method setOption is polymorphic
setOption[T](name: SocketOption[T], value: T): DatagramChannel
so when calling
setOption(StandardSocketOptions.SO_REUSEADDR, true)
scala see that types of arguments are slightly different
StandardSocketOptions.SO_REUSEADDR: SocketOption[java.lang.Boolean]
true: scala.Boolean
and compiler tries to narrow T to the most common type between java.lang.Boolean <: AnyRef and scala.Boolean <: AnyVal which is Any
to fix this issue, you need to either provide explicit type for setOption
setOption[java.lang.Boolean](StandardSocketOptions.SO_REUSEADDR, true)
or use type ascription (then T will be inferred correctly)
setOption(StandardSocketOptions.SO_REUSEADDR, true: java.lang.Boolean)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With