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

后端 未结 4 1650
挽巷
挽巷 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:30

    A Scala String is a java.lang.String but a Scala Boolean is not a java.lang.Boolean. Hence the following works:

    import collection.jcl.Conversions._
    import collection.mutable.{Map => MMap}
    import java.util.Collections._
    import java.util.{Map => JMap}
    
    val jm: JMap[String, java.lang.Boolean] = singletonMap("HELLO", java.lang.Boolean.TRUE)
    
    val sm: MMap[String, java.lang.Boolean] = jm //COMPILES FINE
    

    But your problem is still the issue with the Boolean difference. You'll have to "fold" the Java map into the scala one: try again using the Scala Boolean type:

    val sm: MMap[String, Boolean] = collection.mutable.Map.empty + ("WORLD" -> false)
    val mm = (sm /: jm) { (s, t2) => s + (t2._1 -> t2._2.booleanValue) }
    

    Then mm is a scala map containing the contents of the original scala map plus what was in the Java map

提交回复
热议问题