How to use java map <String, Object> where scala needs map [String, Any]?

How to use / convert map to scala Map [String, Any]?

Java object is recognized as AnyRef in scala.

Is there access to any one line? I would like to avoid repeating the newly created scala maps and link copies.

Thanks in advance.

+3


source to share


2 answers


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

.

+3


source


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

      

+3


source







All Articles