Casting java.util.LinkedHashMap in 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 attributed to scala.collection.mutable.Map

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

+4
source share
2 answers

Importing JavaConversions data does not create java collection type types of scala type types; it provides convenient conversion methods between two different collection hierarchies. In this case, given the import in your question, you can get a mutable scala Map from your java LinkedHashMap using the line:

 val s = mapAsScalaMap(m) 
+7
source

Do not use, 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 latest documentation .

+6
source

Source: https://habr.com/ru/post/1500415/


All Articles