3

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?

Vasil Remeniuk
  • 20,519
  • 6
  • 71
  • 81
Ralph
  • 31,584
  • 38
  • 145
  • 282

1 Answers1

6

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)))
Vasil Remeniuk
  • 20,519
  • 6
  • 71
  • 81
  • I did not know that syntax. Learn something new every day. Thanks. – Ralph Dec 16 '10 at 17:33
  • Is that syntax new? I just looked in a couple of Scala books and could not find it. – Ralph Dec 16 '10 at 17:57
  • 1
    The technique is called `type ascription`, it's not new. You can find some details here: http://stackoverflow.com/questions/2087250/what-is-the-purpose-of-type-ascription-in-scala – Vasil Remeniuk Dec 16 '10 at 18:06
  • I cannot find anything on it in any of my Scala books (Odersky et al, Wampler et al, or Loverdos et al). Thanks. – Ralph Dec 16 '10 at 18:40