Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a java.util.Collections.unmodifiableMap to an immutable Scala Map?

Tags:

scala

I'm trying to convert the parameter map from a ServletRequest to a Scala Map in Scala 2.9.0.1:

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

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

java.lang.ClassCastException: java.util.Collections$UnmodifiableMap cannot be cast to scala.collection.immutable.Map
like image 459
Jeffrey Chung Avatar asked Apr 06 '12 17:04

Jeffrey Chung


1 Answers

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 only lets you implicitly convert to a mutable Scala map:

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

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

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

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

So when you say request.getParameterMap.asInstanceOf[Map[String, Array[String]]], you are really asking Scala to implicitly convert a Java Map into Scala's collection.immutable.Map, which it doesn't want to do since Java's Map is mutable.

like image 68
dhg Avatar answered Nov 03 '22 03:11

dhg