plamb
plamb

Reputation: 5636

Scala Map: is it possible to update a value of Int with a var of Int?

This feels like a dumb question, but here goes:

Consider the following to update a value of Int in a Map with a var of Int

var score: Int = _

val data = Map((
  ("things", "stuff") -> 0),
  (("uwot", "stuff") -> 0),
  (("isee", "stuff") -> 0))

data.map(element => {
  if (element._1._2 == "stuff") {
    score += 1
  }
  element._2 == score
})

In place of

element._2 == score

I've also tried

data(element._1).updated(element._1, score)

and

val result = data.get(element._1)
result == score

to no avail

Any pointers?

Upvotes: 0

Views: 396

Answers (1)

Gangstead
Gangstead

Reputation: 4182

The Map data is immutable and the element you get while mapping the Map is also immutable. You need to assign the result of the data.map(...) to a new val

element._2 == score is a boolean comparison. It is also the last statement of the map function so you are mapping each element (of type Map[[String,String],Int]) into a boolean, and then not assigning it to anything.

I think what you are trying to get is something like this:

val dataOut = data.map( element => {
  if(element._1._2 == "stuff") {
     score += 1
  }
  element._1 -> score
  }
)

Upvotes: 4

Related Questions