繁体   English   中英

Scala案例类在地图内更新值

[英]scala case class update value inside map

我有:

var targets = mutable.HashMap[String, WordCount]()

其中WordCount是案例类:

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

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

每当地图中存在键时,我都在尝试更新count的值,

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

但这行不通。 这样做的正确方法是什么? 请!

调用withCount不会修改case类实例,但会创建一个新的实例类。 因此,您必须再次将新创建的实例存储在地图中:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM