0

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" .

1 Answer 1

4

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.

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

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.