Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use java Map<String, Object> where scala Map[String, Any] is requred?

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.

like image 274
Michal Avatar asked Feb 11 '23 05:02

Michal


2 Answers

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.

like image 66
user5102379 Avatar answered Feb 13 '23 19:02

user5102379


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
like image 32
Dima Avatar answered Feb 13 '23 18:02

Dima