问题
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