As described in this Github issue, Scala Maps that are wrapped as Java Maps are not serializable because scala.collection.convert.Wrappers$MapWrapper
is not serializable.
This issue was fixed in Scala 2.12, but I have to use 2.11 for various reasons. So what is a good workaround for converting a Scala Map to a Java Map without having this serialization error? I have no choice but to return a java map from this function.
My code looks like this:
import scala.collection.JavaConverters.mapAsJavaMapConverter
def doSomethingCool(): util.Map[String, String] = {
// ... Cool processing here ...
// Return results as a Java Map
myScalaMap.asJava
}
I feel like there should be a simple way to work around this issue, but I haven't been able to figure it out...
CodePudding user response:
It is possible to copy a wrapped map with the java.util.HashMap
's copy constructor.
import scala.collection.JavaConverters.mapAsJavaMapConverter
def doSomethingCool(): util.Map[String, String] = {
// ... Cool processing here ...
// Return results as a Java Map
new java.util.HashMap[String, String](myScalaMap.asJava)
}