How to use java map <String, Object> where scala needs map [String, Any]?
May be:
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 keep in mind what is java.lang.Object
equivalent AnyRef
in Scala, not Any
.
source to share
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 that it is needed at the end toMap
because it javaMap.asScala
returns mutable.Map
, and by default the default declaration Map[String,Any]
is immutable.Map
. If you use scala.collection.Map
this instead, you won't need this:
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
source to share