Scala - 更新不可变Vector中的可变映射

时间:2018-05-12 21:04:38

标签: scala dictionary vector

我试图在Scala中构建Vector [Map [String,Any]]。我知道Vector是不可变的,我使用可变Map。

当我尝试这样做时:

def calculate_objectives(pop: Vector[Map[String, Any]]): Unit ={
  for (i <- 0 until pop_size){
    pop(i) = pop(i) + ("weights" -> decode(pop(i)("genome").asInstanceOf[Vector[Int]]))
    pop(i) = pop(i) + ("objective" -> Vector(objective1(pop(i)("weights").asInstanceOf[Vector[Float]]), objective2(pop(i)("weights").asInstanceOf[Vector[Float]])))
  }
}

我没有尝试更改Vector,只是Vector中的Map。这可能吗?

当我尝试编译此代码时,我得到两个相同的错误,我想知道这是否是问题。

Error:(102, 7) value update is not a member of Vector[scala.collection.mutable.Map[String,Any]]
  pop(i) = pop(i) + ("weights" -> decode(pop(i)("genome").asInstanceOf[Vector[Int]]))

1 个答案:

答案 0 :(得分:0)

Map类型为defined in Predef as scala.collection.immutable.Map

如果你想要一个带有可变地图的矢量,那么你必须明确地将该类型声明为collection.mutable.Map,然后你必须update地图,而不是矢量:

import scala.collection.mutable.{Map => MutMap}

def calculate_objectives(pop: Vector[MutMap[String, Any]]): Unit = {
  for (i <- 0 until pop.size){
    pop(i)("weights") = decode(pop(i)("genome").asInstanceOf[Vector[Int]])
    pop(i)("objective") = Vector(
      objective1(pop(i)("weights").asInstanceOf[Vector[Float]]), 
      objective2(pop(i)("weights").asInstanceOf[Vector[Float]])
    )
  }
}

我在这里使用重命名导入将collection.mutable.Map重命名为MutMap。如果需要,您可以在collection.mutable.Map类型中写出完全限定名称pop