映射内的scala案例类更新值

映射内的scala案例类更新值,scala,map,hashmap,case-class,Scala,Map,Hashmap,Case Class,我有: 其中WordCount是一个案例类: var targets = mutable.HashMap[String, WordCount]() 每次在地图上有密钥时,我都会更新count的值 case class WordCount(name: String, id: Int, var count: Option[Double]) { def withCount(v: Double) : WordCount = copy

我有:

其中WordCount是一个案例类:

var targets = mutable.HashMap[String, WordCount]()
每次在地图上有密钥时,我都会更新count的值

case class WordCount(name: String,
                 id: Int,
                 var count: Option[Double]) {

def withCount(v: Double) : WordCount = copy(count = Some(v))
}

但它不起作用。正确的方法是什么?求你了

调用
withCount
不会修改case类实例,而是创建一个新实例。因此,您必须在映射中再次存储新创建的实例:

def insert(w1: String, w2: String, count: Double) = {
    if(targets.contains(w1)){
      var wc = targets.get(w1).getOrElse().asInstanceOf[WordCount]
      wc.withCount(9.0)
    } else{
      targets.put(w1, WordCount(w1, idT(), Some(0.0))
    }
}

注意
targets.get(w1.fold
:get返回
选项[WordCount]
fold
调用其第一个参数,如果其接收器是
None
,否则(即其a
Some
)调用第二个参数并传递
Some
包含的值。

什么是“不工作的”?不是吗?程序是否不正确?aka字数是否正确?为什么在
中使用计数(9.0)
?而且,
insert
没有使用它的
count
参数,我只是想更新那个值。正确的是
wc.count+count
def insert(w1: String, w2: String, count: Double) = {
  val newWC = targets.get(w1).fold {
    WordCount(w1, idT(), Some(0.0)
  } { oldWC =>
    oldWC.withCount(9.0)
  }
  targets.put(w1, newWC)
}