【问题标题】:scala case class update value inside mapscala案例类更新地图内的值
【发布时间】:2014-10-27 12:58:45
【问题描述】:

我有:

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

并且我正在尝试每次在地图中存在键时更新计数值,

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(9.0) 中有 9.0?而insert 不使用它的count 参数
  • 我只是想更新那个值。正确的是wc.count + count

标签: scala map hashmap case-class


【解决方案1】:

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

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:Get 返回一个Option[WordCount]fold 调用它的第一个参数,如果它的接收者是一个None,否则(即它是一个Some)它调用第二个参数并传递它Some 包含的值。

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多