lantis
lantis

Reputation: 349

scala case class update value inside map

I have:

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

Where WordCount is a case class:

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

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

And I'm trying to update the values for count each time the key exists in the map,

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

But it does not working. What is the proper way to do that? please!

Upvotes: 0

Views: 755

Answers (1)

gzm0
gzm0

Reputation: 14842

Calling withCount does not modify the case class instance but creates a new one. Therefore, you'll have to store the newly created instance in the map again:

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

Note the targets.get(w1).fold: Get returns an Option[WordCount], fold calls its first parameter, if its receiver is a None, otherwise (i.e. its a Some) it calls the second parameter and passes it the value the Some contains.

Upvotes: 1

Related Questions