8

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!

2
  • It answered implicitly in @Jean post (see very end) Commented Jun 25, 2014 at 19:25
  • 1
    Voted to reopen—the linked "duplicate" doesn't provide the immutable part, and JavaConversions shouldn't be used, anyway. Commented Jun 25, 2014 at 19:33

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

10 Comments

did you try to use that with a Scala method that takes, say, a Map[Int, Int]? Because I'm getting: actual argument Map<Integer,Integer> cannot be converted to Map<Object,Object> by method invocation conversion
@ErikAllik, yeah, primitives are another set of headaches, but some Predef.Integer2int (or whatever it's called) on the Java side should work. If the OP indicates that they need this, I'll add it to the answer.
My post does not fully answer the question, since a java implementation is required. This answer does. upvoted.
Awesome Thanks! as a note it does require that you get the latest scala standard library 2.11.0 and conforms appears to have been deprecated. However it works for now and the deprecation issue can be a question for another day!
o, that's scary! Now I see what Kotlin people talk about when the say "java interop"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.