How do I convert a java.util.Map to scala.collection.immutable.Map in Java?

和自甴很熟 提交于 2019-12-20 10:47:35

问题


I find lots of people trying to do this, and asking about this but the question is always answered in terms of scala code. I need to call an API that is expecting a scala.collection.immutable.Map but I have a java.util.Map, how can I cleanly convert from the latter to the former in my java code? The compiler disagrees with the sentiment that it is an implicit conversion as it barfs on that when I try it!

Thank you!


回答1:


Getting an immutable Scala map is a little tricky because the conversions provided by the collections library return all return mutable ones, and you can't just use toMap because it needs an implicit argument that the Java compiler of course won't provide. A complete solution with that implicit argument looks like this:

import scala.collection.JavaConverters$;
import scala.collection.immutable.Map;

public class Whatever {
  public <K, V> Map<K, V> convert(java.util.Map<K, V> m) {
    return JavaConverters$.MODULE$.mapAsScalaMapConverter(m).asScala().toMap(
      scala.Predef$.MODULE$.<scala.Tuple2<K, V>>conforms()
    );
  }
}

Writing conversions in Java is a little cleaner with JavaConversions, but on the Scala side essentially everyone hopes that piece of crap will get deprecated as soon as possible, so I'd avoid it even here.



来源:https://stackoverflow.com/questions/24416480/how-do-i-convert-a-java-util-map-to-scala-collection-immutable-map-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!