1

I create a multiple vector like this:

val a = Vector.fill(3,0)(0) 

It outputs:

Vector(Vector(), Vector(), Vector(), Vector(), Vector(), Vector())

I want to append an integer value into the first Vector().

Result should look like this:

Vector(Vector(2), Vector(), Vector(), Vector(), Vector(), Vector()) 

I tried many things from the internet and this way but it doesn't work... a(0).appended(2)

How can I do this?

5
  • 2
    Search for mutable vs immutable collections Commented Oct 28, 2020 at 15:43
  • @MateuszKubuszok what can i find there? There is only the difference between both or the explaining of use of one dimensional vectors... =( Commented Oct 28, 2020 at 16:08
  • 1
    You used immutable vectors and received expected result. You don't know why. That means that you have to learn more about differences between them and what is mutable and what is immutable in Scala. Commented Oct 28, 2020 at 16:09
  • @MateuszKubuszok Thanks, but is there no way to add a value to a multidimensional vector like my question above? Because in an one dimensional vector i can add a value at the end of the vector with concatenation like " :+ "? Commented Oct 28, 2020 at 16:17
  • Dani, hello and welcome to SO! Please take the tour, and read What should I do when someone answers my question? Commented Feb 10, 2021 at 21:46

2 Answers 2

2

Elements cannot be added to immutable types, such as Vector. You can read more about it in one of the articles specified at @Mateusz's comment. When you "add" a new element to a single dimension vector, you basically create a new vector.

If you want to add in the same way, you can create a new vector, for example like this:

val a = Vector.fill(3, 0)(0)
val b = (a.head :+ 2) +: a.tail

Then b will have what you desire. Still, after creating b, a is still the same as created:

Vector(Vector(), Vector(), Vector())

Code run can be found at Scastie.

Sign up to request clarification or add additional context in comments.

1 Comment

This seems a bit simpler and more flexible to me: a.updated(0, a(0) :+ 2) the .head/.tail version is okay for updating the first item but falls down for updating any other position.
1

In vanilla Scala you would have to do something like:

val newA =
  a.zipWithIndex.map {
    case (inner, 0) => inner :+ 2
    case (inner, _) => inner
  }

or as @SethTisue mentioned

val newA = a.update(0, a(0) :+ 2)

However, if you want to modify nested immutable data, something like quicklens can make it easier:

import com.softwaremill.quicklens._
val newA = a.modify(_.at(0)).using(_ :+ 2)

1 Comment

involving zipWithIndex is unnecessarily roundabout. a.updated(0, a(0) :+ 2) will do the trick

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.