28

How do I convert java.util.Map[String, Object] to scala.collection.immutable.Map[String, Any], so that all values in the original map (integers, booleans etc.) are converted to the right value to work well in Scala.

Eugene Yokota
  • 94,654
  • 45
  • 215
  • 319
IttayD
  • 28,271
  • 28
  • 124
  • 178
  • I don't know scala, but can't you do if(objecdt instanceof Integer)... and so on? It's not the best approach but it should work... Maybe you can wrap the objects and use the visitor pattern... – pakore Jun 27 '10 at 12:12

3 Answers3

36

As VonC says, scala.collections.JavaConversion supports mutable collections only, but you don't have to use a separate library. Mutable collections are derived from TraversableOnce which defines a toMap method that returns an immutable Map:

import scala.collection.JavaConversions._

val m = new java.util.HashMap[String, Object]()
m.put("Foo", java.lang.Boolean.TRUE)
m.put("Bar", java.lang.Integer.valueOf(1))

val m2: Map[String, Any] = m.toMap
println(m2)

This will output

Map(Foo -> true, Bar -> 1)
Michel Krämer
  • 14,197
  • 5
  • 32
  • 32
  • That answers my question. In my more specific case, I needed to map over the values of the map, so m.map{...}(breakOut) also did the trick – IttayD Jun 27 '10 at 12:48
1

The JavaConversions package of Scala2.8 deals only with mutable collections.

The scalaj-collection library might help here.

java.util.Map[A, B]       #asScala: scala.collection.Map[A, B]
                          #asScalaMutable: scala.collection.mutable.Map[A, B]
                          #foreach(((A, B)) => Unit): Unit
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
1

In order to convert convert java.util.Map[String, Object] to scala.collection.immutable.Map[String,Object] , you need to simple import below statement in Scala Project and clean build.

import collection.JavaConversions._

Refer to below code:

var empMap= Map[String.Object]()
var emp= new Employee(empMap)  // Employee is java  POJO in which,passing scala map  to overloaded constructor for setting default values.