How to use/convert Map to scala Map[String, Any]?
Java Object is recognized as AnyRef in scala.
Is there any one line conversion available? I would like to avoid iterating over newly created scala Map and copying refs.
Thanks in advance.
May be this:
val jmap = new HashMap[String, Object]
jmap.put("1", new Date)
import scala.collection.JavaConverters._
val smap = jmap.asScala.mapValues(_.asInstanceOf[Any]).toMap
test(smap)
def test(m: Map[String, Any]): Unit = {
println(m)
}
Also be aware that java.lang.Object
is equivalent to AnyRef
in Scala, not Any
.
This should work:
import scala.collection.JavaConversions._
val javaMap = new HashMap[String,Object]
val scalaMap: Map[String,Any] = javaMap.toMap
Or, if you don't like "the magic of implicits", do this:
import scala.collection.JavaConverters._ // note, this is a different import
val javaMap = new HashMap[String, Object]
val scalaMap: Map[String, Any] = javaMap.asScala.toMap // this .asScala is what the other version does implicitly
Note also, that the toMap
in the end is needed because javaMap.asScala
returns a mutable.Map
, and the Map[String,Any]
declaration defaults to an immutable.Map
by default.
If you use scala.collection.Map
instead, you won't need it:
import scala.collection.Map
import scala.collection.JavaConversions._
val javaMap = HashMap[String, Object]
val scalaMap: Map[String,Any] = javaMap // voila!
or explicitly
import scala.collection.Map
import scala.collection.JavaConverters._
val javaMap = HashMap[String, Object]
val scalaMap: Map[String, Any] = javaMap.asScala
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