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?

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
gknauth
  • 2,310
  • 2
  • 29
  • 44
  • possible duplicate of [Convert Scala Set into Java (java.util.Set)?](http://stackoverflow.com/questions/2233576/convert-scala-set-into-java-java-util-set) – om-nom-nom Apr 29 '14 at 14:19
  • Although Set was mentioned in that question, in fact the same goes for most Scala -> Java collections. – om-nom-nom Apr 29 '14 at 14:19

1 Answers1

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

Community
  • 1
  • 1
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
  • 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). – gknauth Apr 28 '14 at 21:06
  • 4
    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. – som-snytt Apr 28 '14 at 22:43
  • 1
    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. – Travis Brown Apr 29 '14 at 00:48
  • 1
    @som-snytt Sorry, I was relying on the built-in documentation too much. Edited to be more specific. – Justin Pihony Apr 29 '14 at 14:12
  • Thanks, som-snytt, I'll follow your suggestion going forward. – gknauth Apr 29 '14 at 15:15