0

I have an array

val doot = Array("a", "b", "c")

I want to replace the 2nd index with the letter "z", but I do not want to modify doot. I want to create a new array, as that seems to be the idiom in scala.

So far, I can only modify the array with update

doot.update(1, "z") // But now doot is modified directly, not ideal!

Does scala offer a way to do this?

3
  • 1
    To be clear on language: you can't "replace" a value in an immutable array since it's immutable. i.e. cannot change. Commented Jul 11, 2016 at 2:52
  • 8
    To be further clear on language: There is no such thing as an "immutable array" in scala. There is only one Array, and it is mutable. Commented Jul 11, 2016 at 3:03
  • Well, that's good to know! My wording was off yeah, the point was that I cannot replace a value in an immutable array.. I wanted to create a new array with that value replaced. Commented Jul 11, 2016 at 3:38

1 Answer 1

7
scala> val doot = Array("a", "b", "c")
doot: Array[String] = Array(a, b, c)

scala> val eoot = doot.updated(1, "z")
eoot: Array[String] = Array(a, z, c)

scala> doot
res0: Array[String] = Array(a, b, c)

scala> eoot
res1: Array[String] = Array(a, z, c)
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.