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.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

3 Comments

excellent! I noticed conversion doesn't work recursively though
@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.
I could but wouldn't it be nice extension for java conversion library to handle it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.