2017-02-24 54 views
0

我正在嘗試更新數組中的哈希映射,但無法這樣做。哈希映射在scala中追加

def incrementCount(combiners: Array[Combiner], row: Row): Array[Combiner] = { 
    val tempMapTypes = new scala.collection.mutable.HashMap[String, (String, Array[String])] 
    for (i <- 0 until row.length) { 
     val array = getMyType(row(i), tempMapTypes) 
     for (elem <- tempMapTypes) { 
     combiners(i).mapTypes.update(elem._1,elem._2) <<<< this update doesnt work for me, always mapTypes is empty 
     } 
    } 
    } 

這是合班

case class Combiner(<other variables>, mapTypes: mutable.HashMap[String, (String, Array[String])]) 
     combiners 
     } 

這是怎麼回事,它的另一種方法得到了初始化...

val mapTypes = new scala.collection.mutable.HashMap[String, (String, Array[String])] 
combiners += new Combiner(....,mapTypes) 

正如上面提到的,這種情況下的初始化之後類,如何追加mapTypes,上述更新代碼似乎不適合我。

回答

0

如果你想用你的更新代碼,你可以對Combiner定義++=方法:

class Combiner(..., mapTypes: mutable.HashMap[String, (String, Array[String])]) { 

    ... 

    def ++=(otherMapTypes: mutable.HashMap[String, (String, Array[String])]): Unit = 
    this.mapTypes ++= otherMapTypes 

} 

然後你就可以做到以下幾點:

for(i <- row.length) { 
    combiners(i) ++= tempMapTypes 
}