1

How can I add to immutable map without using vars? How to bind immutable to a new value? When trying the following code I get an error:

"reassignment to val"

my code:

object Play {

  def main(args: Array[String]): Unit = {
          test1()
  }

  def test1() {
val pairs = Array(("a", 1), ("b", 2), ("c", 3), ("d", 4))
val m = Map[String, Int]()

for (x <- pairs) {
    m = addToMap (x, m)
}
  }

  def addToMap(pair: (String, Int), map: Map[String, Int]): Map[String, Int] = {
      map + (pair._1 -> pair._2)
  }

}
1
  • Use foldLeft or a tailrec method. Commented Mar 24, 2013 at 18:43

4 Answers 4

2

If you want to reassign an immutable map you need to make it a var:

var m = Map[String, Int]()
Sign up to request clarification or add additional context in comments.

Comments

2

Or use à mutable data structure like :

scala.collection.mutable.Map

But you won't be able de reassign the variable however!

Comments

2

There are a few options.

The most common approach is just to use a var when you're building up a structure. This is often the simplest and most readable approach

Another is to use recursive structures, either by writing a recursive function call directly or using something like fold. (I would generally recommend you use standard functions like folds and maps rather than doing your own iterations.)

Another useful idiom for you would be to use something like toMap. This has already been mentioned for the case where you have an existing array like you do, but it can also be useful in conjunction with the foreach loop (or the equivalent functions). For example,

( for (x <- xs)
  yield (toKey(x), toVal(y))
).toMap

If the values are static, you can also just do something like this.

Map("a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4)

Personally, when I'm just working with a temporary local map, I find a mutable map is often the most appropriate. It's valuable to understand how to do things in a functional way, and I think everybody should learn Haskell, but Scala's m(x) = y syntax for mutable maps can often lead to extremely simple & concise code.

Scala is intentionally a mixed-paradigm language. My recommendation is to reach for the immutable, functional approaches first but don't be afraid to use the imperative features when they make things simpler—unless there are threads involved.

Comments

1

All that you need is convertion from Array to Map:

val pairs = Array(("a", 1), ("b", 2), ("c", 3), ("d", 4))
val m = pairs.toMap

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.