1

I have a ConcurrentHashMap object defined as below:

import scala.collection.JavaConversions._
val storage: ConcurrentMap[String,ConcurrentMap[Int,ConcurrentMap[String,Double]]] =
new ConcurrentHashMap[String,ConcurrentHashMap[Int,ConcurrentHashMap[String,Double]]]

And Scala (2.8.1) complains at compilation with the following error:

found   : java.util.concurrent.ConcurrentHashMap[String,java.util.concurrent.ConcurrentHashMap[String,String]]
required: scala.collection.mutable.ConcurrentMap[String,scala.collection.mutable.ConcurrentMap[String,String]]

But when I try the following code, it works:

val storage: ConcurrentMap[String,Double] = new ConcurrentHashMap[String,Double]

I appreciate your comment how to fix this error.

1 Answer 1

2

Implicit conversions, such as the one provided by JavaConversions, work at the instance level rather than the type level. So, while the outermost map can be converted, the inner maps will not be.

There isn't a way to directly have the nested case implicitly converted. And, unfortunately, it appears that the most specific implicit is not being correctly selected in the following examples:

scala> val storage = new ConcurrentHashMap[String,ConcurrentHashMap[Int,ConcurrentHashMap[String,Double]]]
storage: java.util.concurrent.ConcurrentHashMap[String,java.util.concurrent.ConcurrentHashMap[Int,java.util.concurrent.ConcurrentHashMap[String,Double]]] = {}

scala> import scala.collection.JavaConverters._

scala> for ((i, m) <- storage.asScala; (j, m2) <- m.asScala; (k, l) <- m2.asScala) yield ((i, j) -> (k, l))
res0: scala.collection.mutable.Map[(String, Int),(String, Double)] = Map()

scala> import scala.collection.JavaConversions._

scala> for ((i, m) <- storage; (j, m2) <- m; (k, l) <- m2) yield ((i, j) -> (k, l))                        
res3: scala.collection.mutable.Map[(String, Int),(String, Double)] = Map()

So, in final analysis, I predict a lot of type annotations in your future (the for comprehensions above would probably work with explicit type ascription, but I'm too sleepy to type it all out.)

Not the answer you're looking for? Browse other questions tagged or ask your own question.