How do you convert java.util.Collections.unmodifiableMap into an immutable Scala map?

I am trying to convert a parameter map from ServletRequest to a Scala map in Scala 2.9.0.1:

val params = request.getParameterMap.asInstanceOf[Map[String, Array[String]]] 

I imported collection.JavaConversions._, and at runtime this is thrown:

 java.lang.ClassCastException: java.util.Collections$UnmodifiableMap cannot be cast to scala.collection.immutable.Map 
+6
source share
1 answer

How about just calling .toMap on it?

 import collection.JavaConversions._ val x = java.util.Collections.unmodifiableMap[Int,Int](new java.util.HashMap[Int,Int]()) val y: Map[Int,Int] = x.toMap //y: Map[Int,Int] = Map() 

Without calling toMap , JavaConversions allows you to implicitly convert to a Scala mutable map:

 scala> val z: collection.mutable.Map[Int,Int] = x z: scala.collection.mutable.Map[Int,Int] = Map() 

Presumably this is because the Java Map is mutable, so it should only be represented in Scala as mutable.Map , unless you explicitly convert it to immutable.Map .

Note that when you just say Map in Scala, you are really talking about collection.immutable.Map , since Predef aliases Map as follows:

 scala> Map() res0: scala.collection.immutable.Map[Nothing,Nothing] = Map() 

So, when you say request.getParameterMap.asInstanceOf[Map[String, Array[String]]] , you really ask Scala to implicitly convert Java Map to Scala collection.immutable.Map , which it does not want to do since Java Map is mutable.

+8
source

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


All Articles