Scala Auto Boxing and Java Map

My Java method takes a type argument Map<Long, Foo>. I am trying to write unit test for this method in Scala 2.8.1 and pass to literal Map[Long, Foo].

My code is as follows:

import collection.JavaConversions._
x.javaMethod(asJavaMap(Map(1L -> new Foo, 2L -> new Foo)))

The compiler tells 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 to do it?

+3
source share
1 answer

The error indicates that a Scala map with a type scala.Longcannot be implicitly converted to a 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 can specify the required type manually:

x.javaMethod(asJavaMap(Map((1:java.lang.Long) -> new Foo, (2:java.lang.Long) -> new Foo)))
+6
source

Source: https://habr.com/ru/post/1780708/


All Articles