Dani
Dani

Reputation: 11

Scala append value to multiple vector

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?

Upvotes: 1

Views: 334

Answers (2)

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

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)

Upvotes: 1

Tomer Shetah
Tomer Shetah

Reputation: 8529

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.

Upvotes: 2

Related Questions