更新时间:2023-09-11 23:24:16
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.