Converting Map[String, Double] to java.util.Map[String, java.lang.Double]

前端 未结 3 1891
野趣味
野趣味 2021-01-14 15:15

I thought we can rely on implicit conversion which converts scala.Double to java.lang.Double. So I tried the following:

import scal         


        
3条回答
  •  悲&欢浪女
    2021-01-14 15:50

    The issue here is that scala.Double is a primitive (equivalent to Java double) while java.lang.Double is a class. They are not at all the same thing. The JavaConverters converts between Java Map and Scala Map, not their contents. This works:

    import scala.collection.JavaConverters._
    
    object Main {
    
      def main(args: Array[String]): Unit = {
        val m = Map("10" -> 20.0)
        doSome(mapConv(m))
        doSome2(m.asJava)
      }
      def doSome(m: java.util.Map[java.lang.String, java.lang.Double]) = println(m)
      def doSome2(m: java.util.Map[java.lang.String, Double]) = println(m)
    
      def mapConv(msd: Map[String, Double]): java.util.Map[java.lang.String, java.lang.Double] = {
        msd.map { case (k, v) => (k -> new java.lang.Double(v)) }.asJava
      }
    }
    

提交回复
热议问题