6

I have a Scala function f(s1: String, s2: String): Map[String,String]

I want to allow a colleague coding in Java to call a Java method I'm writing:

HashMap<String, String> f(String s1, String s2)

This calls my Scala function. What I've found, on the Java side, is that Scala has returned a scala.collection.immutable.Map.

How do I make a Java HashMap out of it? Or should I be doing something else?

2
  • possible duplicate of Convert Scala Set into Java (java.util.Set)? Commented Apr 29, 2014 at 14:19
  • Although Set was mentioned in that question, in fact the same goes for most Scala -> Java collections. Commented Apr 29, 2014 at 14:19

1 Answer 1

10

I think what you are looking for is here. Specifically the mapAsJavaMap method.

Where the preferred usage is explained in this SO question Using imported implicits and asJava

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

5 Comments

Thanks, Justin. That got me on the right path. Over on the Scala side I did this: val im = f(s1,s2); val mm = collections.mutable.Map(im:toSeq: _*); JavaConversions.mapAsJavaMap(mm) and that resulted in a mutable map on the Java side (which I think is what Java was looking for, and my map was immutable).
Actually, you want import JavaConverters._ and m.asJava. This is common wisdom and must have a duplicate question if someone could find it. The style guide is to use converters and explicitly ask for the conversion.
Yeah, sorry, but I'm with som-snytt—this is essentially a link-only answer that suggests an unidiomatic use of a package that most Scala developers agree should be avoided.
@som-snytt Sorry, I was relying on the built-in documentation too much. Edited to be more specific.
Thanks, som-snytt, I'll follow your suggestion going forward.

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.