Scala autoboxing and Java Map
-
11-10-2019 - |
Pergunta
I have a Java method takes an argument of type Map<Long, Foo>
. I am trying to write a unit test for that method in Scala 2.8.1 and pass in a literal Map[Long, Foo]
.
My code looks like this:
import collection.JavaConversions._
x.javaMethod(asJavaMap(Map(1L -> new Foo, 2L -> new Foo)))
The compiler is giving me the following error:
error: type mismatch;
found : scala.collection.immutable.Map[scala.Long,Foo]
required: scala.collection.Map[java.lang.Long,Foo]
I also tried it with
import collection.JavaConverters._
x.javaMethod(Map(1L -> new Foo, 2L -> new Foo))
and
import collection.JavaConversions._
x.javaMethod(Map(1L -> new Foo, 2L -> new Foo))
and got the error:
error: type mismatch;
found : scala.collection.immutable.Map[scala.Long,Foo]
required: java.util.Map[java.lang.Long,Foo]
How do I do this?
Solução
The error says that Scala map with scala.Long
key type cannot be implicitly converted to Java map based on java.lang.Long
:
found : scala.collection.immutable.Map[scala.Long,Foo]
required: scala.collection.Map[java.lang.Long,Foo]
As a workaround, you may specify the required type manually:
x.javaMethod(asJavaMap(Map((1:java.lang.Long) -> new Foo, (2:java.lang.Long) -> new Foo)))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow