簡體   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