2011-04-19 90 views
1

我定義爲以下的ConcurrentHashMap對象:斯卡拉Java的深度地圖轉換(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] 

我感謝您的評論如何解決此錯誤。

回答

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

所以,歸根結底,我在你的未來預測了很多類型的註解(在用於推導上面會可能與明確的類型歸屬一起工作,但是我太困了,不能全部輸入。)