7
import scala.collection.JavaConversions._
val m = new java.util.LinkedHashMap[String,Int]
val s: scala.collection.mutable.Map[String,Int] = m.asInstanceOf[scala.collection.mutable.Map[String,Int]]

returns the following error

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to scala.collection.mutable.Map

What is wrong here and how to do this casting? I tried also scala.collection.JavaConverters._ getting the same error.

deepkimo
  • 3,187
  • 3
  • 23
  • 21

2 Answers2

10

Don't cast, just use the implicit conversion:

val s: scala.collection.mutable.Map[String,Int] = m

Edit: some (or most) prefer converters because they are explicit:

scala> val m = new java.util.LinkedHashMap[String,Int]
m: java.util.LinkedHashMap[String,Int] = {}

scala> m.put("one",1)
res0: Int = 0

scala> import scala.collection.JavaConverters._
import scala.collection.JavaConverters._

scala> val s = m.asScala
s: scala.collection.mutable.Map[String,Int] = Map(one -> 1)

Read the latest documentation.

som-snytt
  • 39,429
  • 2
  • 47
  • 129
9

Importing the JavaConversions stuff doesn't make java's collection types instaces of the scala collection types, it provides handy conversion methods between the two distinct collection hierarchies. In this case, given the import in your question, you can get a mutable scala Map from your java LinkedHashMap with the line:

val s = mapAsScalaMap(m)
Shadowlands
  • 14,994
  • 4
  • 45
  • 43
  • excellent! I noticed conversion doesn't work recursively though – nir Jul 06 '15 at 20:58
  • @nir It doesn't, but now that you have a Scala collection, you can call the map method on it and handle nested collections yourself easily enough. – Shadowlands Jul 06 '15 at 21:31
  • I could but wouldn't it be nice extension for java conversion library to handle it? – nir Jul 06 '15 at 21:35