Avoid `Boolean.box`

856 views Asked by At

I am calling a java method from io.netty.bootstrap.BootStrap that has the following signature:

public <T> B option(ChannelOption<T> option, T value)

I am using the following code to call this method:

b.option(ChannelOption.SO_KEEPALIVE, true);

And this fails to compile with the following error:

Error:(57, 30) type mismatch;
 found   : io.netty.channel.ChannelOption[Boolean]
 required: io.netty.channel.ChannelOption[Any]
Note: Boolean <: Any, but Java-defined class ChannelOption is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
      b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
                         ^

I don't fully understand what this says, but I understand it's complaining about getting a boolean since it was parametrized with Any instead of Boolean. So I tried the following code and it works:

b.option(ChannelOption.SO_KEEPALIVE, Boolean.box(true));

This compiles and works. Is there a way to make this prettier without the box call?

Can anyone translate that compiler error?

Thank you.

1

There are 1 answers

5
Gabriele Petronella On BEST ANSWER

Java generics are invariant in scala, so you cannot pass a scala Boolean and have the type inferred as you would expect. Explicitly annotating the type should fix it:

b.option[java.lang.Boolean](ChannelOption.SO_KEEPALIVE, true)