Is this the special case that Array can change

scala> val s = Array("hello","world")
val s: Array[String] = Array(hello, world)

scala> s(0)
val res0: String = hello

scala> s(0) = "goodbye"

scala> s
val res2: Array[String] = Array(goodbye, world)

As you see even defined with “val” the Array’s content can be changed.
Is this a special case in scala? thank you.

Is not a special case.

val s = Array("hello","world")

This means that the s reference is immutable, it will always point to the same Array
But Array is mutable, you can always change its contents (although its size is fixed).

I am reading the different books including “learning scala”, “programming in scala 4th” and “scala for the impatient 2nd”. there seems exist the conflicts. such as:

scala> b.insert(2,9,9,9)
                    ^
       error: too many arguments (found 4, expected 2) for method insert: (index: Int, elem: Int): Unit

The book says above can work, but it doesn’t actually.

And this:

scala> b += (3,3,3)
         ^
       warning: method += in trait Growable is deprecated (since 2.13.0): Use `++=` aka `addAll` instead of varargs `+=`; infix operations with an operand of multiple args will be deprecated
val res11: b.type = ArrayBuffer(2, 2, 9, 3, 4, 3, 3, 3)

it does work but a warning was issued.
I am using 2.13.7.

But list content seems can’t be updated.

scala> val li = List(3,1,2,4)
val li: List[Int] = List(3, 1, 2, 4)

scala> li(0)
val res13: Int = 3

scala> li(0) = 9
       ^
       error: value update is not a member of List[Int]
       did you mean updated?

Because List is immutable.

Remember when you asked when to use Array VS List that I said never to use Arrays because among a bunch of other reasons, they were mutable: When to use Array and when to use List - #3 by BalmungSan

1 Like

thanks. just some books introduced the Array, for which I did some test on repl.