How to convert from from java.util.Map to a Scala Map

后端 未结 4 1651
挽巷
挽巷 2021-02-07 12:58

A Java API returns a java.util.Map;. I would like to put that into a Map[String,Boolean]

So imagine w

4条回答
  •  抹茶落季
    2021-02-07 13:42

    I think I have a partial answer...

    If you convert the java map to a scala map with the java types. You can then map it to a scala map of scala types:

    val javaMap = new java.util.TreeMap[java.lang.String, java.lang.Boolean]
    val temp = new collection.jcl.MapWrapper[java.lang.String,java.lang.Boolean] {
        override def underlying = javaMap
    }
    val scalaMap = temp.map{
        case (k, v) => (k.asInstanceOf[String] -> v.asInstanceOf[Boolean])
    }
    

    The flaw in this plan is that the type of scalaMap is Iterable[(java.lang.String, Boolean)] not a map. I feel so close, can someone cleverer than me fix the last statement to make this work?!

提交回复
热议问题