Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting java.util.LinkedHashMap to scala.collection.mutable.Map

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.

like image 414
deepkimo Avatar asked Sep 04 '13 01:09

deepkimo


2 Answers

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)
like image 65
Shadowlands Avatar answered Oct 10 '22 09:10

Shadowlands


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.

like image 34
som-snytt Avatar answered Oct 10 '22 11:10

som-snytt