0

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?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
plamb
  • 5,636
  • 1
  • 18
  • 31

1 Answers1

4

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
  }
)
Gangstead
  • 4,152
  • 22
  • 35
  • 1
    Thank you for the answer, I'd never seen that '->' operator used like that before. What ended up working for my use case was doing a .map on a List then using the "element -> score" to produce a Map with the updated scores – plamb Feb 17 '15 at 07:23