I have a Java class that needs to stay in Java for a variety of reasons. It is calling a method on a class implemented with a Scala trait and a Scala implementation that needs a Scala immutable map. Yes, I have seen how to use implicit and explicit code if I have the Java Map and I am doing the converting in Scala code, but I am trying to do the conversion from Java code and have seen nothing like that on Stack Overflow.
I am using Eclipse and the project has the Scala nature added to it. I tried importing scala.collection.JavaConverters, and Eclipse just gave me an error saying it couldn't find the class even though I can see the class when I open up the scala-library in the Scala Library container. I am using Scala 2.11.8
How can I write explicit code that converts the Java Map into the Scala Map in Java code?
You can use myMap. toMap to convert an a mutable map into immutable in Scala 2.8 and later versions.
Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.
Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. HashMap implements immutable map and uses hash table to implement the same.
Why not simply use toMap.
Something Like :
import scala.collection.JavaConverters._
// asScala creates mutable Scala Map
// toMap after asScala creates immutable Map
val scalaImmutableMap = javaMap.asScala.toMap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With