Scala Java深度图转换(ConcurrentHashMap)

时间:2011-04-19 02:58:50

标签: scala scala-2.8 scala-collections

我有一个ConcurrentHashMap对象,如下所示:

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

Scala(2.8.1)在编译时抱怨以下错误:

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

但是当我尝试以下代码时,它可以工作:

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

感谢您发表评论如何解决此错误。

1 个答案:

答案 0 :(得分:2)

隐式转换(例如JavaConversions提供的转换)在实例级而不是类型级工作。因此,虽然可以转换最外面的地图,但内部地图不会被转换。

没有办法直接将嵌套大小写隐式转换。并且,遗憾的是,在以下示例中似乎未正确选择最具体的隐式:

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()

所以,在最后的分析中,我预测你未来会有很多类型的注释(上面的理解可能与明确的类型归属有关,但是我太困了,不能全部输入。)