1
votes

There are a lot of similar questions to this about Scala/Java mutable/immutable conversions but I couldn't find this exact question.

I have a Java method which is consuming a scala.collection.immutable.Map m. I need to insert/remove some entries and then return the new scala map (immutable or mutable -- it doesn't matter).

Currently I'm doing the following:

java.util.HashMap<T1, T2> javaMap = new java.util.HashMap<>(
                (Map<T1, T2>) JavaConverters.mapAsJavaMapConverter(m).asJava());  
javaMap.put(k1, v1);
javaMap.remove(k2);
return scala.collection.JavaConverters.mapAsScalaMapConverter(javaMap).asScala();

But having to convert between a map-types twice is quite ugly. I think the ideal solution is to convert the immutable scala map to a mutable scala map, then do the operations and return it, but I couldn't find any documentation or examples about converting an immutable scala map to a mutable scala map in Java.

Any help is much appreciated.

1

1 Answers

1
votes

You could try to directly use the scala immutable map:

return m
    .$plus(Tuple2.apply(k1, v1))
    .$minus(k2)

The syntax is not pretty as you can see, and sometimes IDEs complain when using scala methods in java, but I don't see other options if you want to avoid the back and forth conversion.