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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With