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

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

    useJavaMap.scala

    import test._
    import java.lang.Boolean
    import java.util.{Map => JavaMap}
    import collection.jcl.MapWrapper
    
    object useJavaMap {
      def main(args: Array[String]) {
        var scalaMap : Map[String, Boolean] = Map.empty
        scalaMap = toMap(test.testing())
        println(scalaMap)
      }
    
      def toMap[K, E](m: JavaMap[K, E]): Map[K, E] = {
        Map.empty ++ new MapWrapper[K, E]() {
          def underlying = m
        }
      }
    }
    

    test/test.java

    package test;
    
    import java.util.*;
    
    public class test {
        public static Map testing() {
            Map x = new HashMap();
            x.put("Test",Boolean.FALSE);
            return x;
        }
        private test() {}
    }
    

    Commandline

    javac test\test.java
    scalac useJavaMap.scala
    scala useJavaMap
    > Map(Test -> false)
    

提交回复
热议问题