1

I am learning immutable types in Scala and am struggling to get this elementary task done. I simply need to append to an array of doubles that is within a map. I do not want to use ArrayBuffer.

My ultimate goal is to make an adjacency matrix. When I append a new item to the map (an (Int, double) tuple) I want to increase the size of each array within the map--essentially increasing the dimension of the matrix.

var map = Map[Int, Array[Double]]()
map += (0 -> new Array[Double](5))

// HOW TO DO THIS
map(0) = map(0) :+ 0.01

for ((i, a) <- map) {
    print(i + ": ")
    for (d <- a) print(d + ", ")
}

What I have written above does not compile. However map(0) :+ 0.01 alone will but it does not achieve my goal of appending to an immutable array within a map.

1
  • can you please clarify the question a bit more. Commented Jul 13, 2018 at 13:00

1 Answer 1

2

Because it is immutable Map, you can't change the value in place, as you've tried to do using map(0) = map(0) :+ 0.01. The one of the possible solutions is using updated method, which returns updated map (all methods like add, remove, modify in immutable data structures return new data struture):

map = map.updated(0, map(0) :+ 0.01)

Some examples to prove:

var map = Map[Int, Array[Double]]()
map += (0 -> new Array[Double](5))
map = map.updated(0, map(0) :+ 0.01)
map(0) // res1: Array[Double] = Array(0.0, 0.0, 0.0, 0.0, 0.0, 0.01)
map = map.updated(0, map(0) :+ 0.02)
map(0) // res2: Array[Double] = Array(0.0, 0.0, 0.0, 0.0, 0.0, 0.01, 0.02)
Sign up to request clarification or add additional context in comments.

2 Comments

It can't. I'll give some examples soon
Okay sorry to give you the run around but I can confirm that your solution does work and does not drop entries in the map. Thanks for your help.

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.