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

I find many people trying to do this and ask about it, but scala code always answers the question. I need to call an API that expects scala.collection.immutable.Map, but I have java.util.Map, how can I completely convert from the latter to the former in my java code? The compiler does not agree with the opinion that this is an implicit conversion, because it causes it when you try!

Thanks!

+6
source share
1 answer

Getting an immutable Scala map is a bit more complicated because the transformations provided by the collection library return all returning mutable ones, and you cannot just use toMap because it needs an implicit argument, which of course the Java compiler will not provide. A complete solution with this implicit argument is as follows:

 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, in fact, everyone hopes that a piece of crap will become obsolete as soon as possible, so I would avoid it even here.

+14
source

Source: https://habr.com/ru/post/971352/


All Articles