Jeffrey Chung
Jeffrey Chung

Reputation: 19497

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

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

Upvotes: 7

Views: 11047

Answers (1)

dhg
dhg

Reputation: 52681

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.

Upvotes: 8

Related Questions