How can I convert Scala Map to Java Map with scala.Float to java.Float k/v conversion

rvange picture rvange · May 16, 2013 · Viewed 41.7k times · Source

I would like to be able to perform the following, but it fails in the call to useMap. How can I perform this conversion?

scala> import scala.collection.JavaConversions._
import scala.collection.JavaConversions._

scala> import scala.collection.JavaConverters._
import scala.collection.JavaConverters._

scala> def useMap(m: java.util.Map[java.lang.Integer, java.lang.Float]) = m
useMap: (m: java.util.Map[Integer,Float])java.util.Map[Integer,Float]

scala> val v: Map[Int, Float] = Map()
v: Map[Int,Float] = Map()

scala> useMap(v)
<console>:10: error: type mismatch;
 found   : scala.collection.immutable.Map[Int,scala.Float]
 required: java.util.Map[Integer,java.lang.Float]
              useMap(v)
                     ^

It seems to work with Map[String, String], but not Map[Int, Float].

Answer

rvange picture rvange · May 17, 2013

The solution linked to by @pagoda_5b works: Scala convert List[Int] to a java.util.List[java.lang.Integer]

scala> import collection.JavaConversions._
import collection.JavaConversions._

scala> val m = mapAsJavaMap(Map(1 -> 2.1f)).asInstanceOf[java.util.Map[java.lang.Integer, java.lang.Float]]
m: java.util.Map[Integer,Float] = {1=2.1}

scala> m.get(1).getClass
res2: Class[_ <: Float] = class java.lang.Float