cool learner
cool learner

Reputation: 1

How to update a specific element in Immutable Array using Scala

I have immutable array in scala as below:

val myArray = Array.fill(3)(null)

So what I want is that updating some location in the array. Such as a second location. I tried this way but it is always only returning an array of one value

myArray(0) = "2"

myArray(1) = "3"

It is only returning first element for some reasons which is "2" .

Upvotes: 0

Views: 439

Answers (1)

Aivean
Aivean

Reputation: 10882

Arrays in Scala are mutable.

val myArray = Array.fill[String](3)(null)
// myArray is Array(null, null, null)

myArray(1) = "1"

// myArray is now Array(null, 1, null)

If you want an immutable replacement for the Array, look at the Vector:

val myVec = Vector.fill[String](3)(null)
// myVec is Vector(null, null, null)

myVec.updated(1, "1")  // returns NEW Vector(null, 1, null)

// here myVec is still Vector(null, null, null)

Note, that updating Vector is slower than mutating the Array, that is the price of immutability.


Another alternative is to use an immutable ArraySeq in (scala 2.13):

val myArrSeq = ArraySeq.fill[String](3)(null)
// myArrSeq is ArraySeq(null, null, null)

myArrSeq.updated(1, "1")  // returns NEW ArraySeq(null, 1, null)

// myArrSeq is still ArraySeq(null, null, null)

It behaves the same way as Vector does, and is backed by plain array internally, but, (important!), each update copies the whole sequence ( O(N) ), which is not acceptable in most scenarios.


Also, check this related question.

Upvotes: 4

Related Questions