4

I understand that val keyword determines the underlying variable is a Immutable type (Cannot be reassigned later time). Now i come across a paragraph in programming in scala (Chapter 3, Next steps in scala - parameterize arrays with types), it states

val greetStrings: Array[String] = new Array[String](3)
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!\n"

These three lines of code illustrate an important concept to understand about Scala concerning the meaning of val. When you define a variable with val, the variable can’t be reassigned, but the object to which it refers could potentially still be changed. So in this case, you couldn’t reassign greetStrings to a different array; greetStrings will always point to the same Array[String] instance with which it was initialized. But you can change the elements of that Array[String] over time, so the array itself is mutable.

so its valid to change the elements of array. And its invalid if we define like this

greetStrings = Array("a","b","c")

It satisfies the below statement

When you define a variable with val, the variable can’t be reassigned, but the object to which it refers could potentially still be changed.

but if i declare something like this

val str = "immutable string"

By the definition given in the book

what it means object to which it refers could potentially still be changed in the above line of code ??

RameshVel
  • 64,778
  • 30
  • 169
  • 213

1 Answers1

10

Declaring a val does not guarantee or even imply an immutable type. It only declares what you might call in Java a final variable. The identifier cannot be re-assigned, but the value may be of a mutable type.

In your example of a string value, you have both a val and an immutable type, String. So this identifier is neither re-assignable nor modifiable (immutable).

Elmo
  • 358
  • 2
  • 8
  • thanks Elmo.. So "object to which it refers could potentially still be changed" only applicable for arrays declared with val(immutable).... ?? – RameshVel Jul 27 '10 at 09:14
  • 1
    Hi Ramesh. In Scala, Array is mutable (but you can't change it's length). If you want an immutable implementation of a collection, you could try List. – Elmo Jul 27 '10 at 09:20
  • 2
    List exists in both a mutable and immutable version. The mutable version is called ListBuffer. Compare with String and StringBuffer/StringBuilder in java, where String is immutable and StringBuffer/StringBuilder is mutable. See http://stackoverflow.com/questions/1241166/preferred-way-to-create-a-scala-list – oluies Jul 27 '10 at 19:09
  • Note that `List` is *not* the same kind of thing as an immutable `Array`. A `List` behaves like a linked list - you do not have effient random access like in an array. If you need an immutable array, use `scala.collections.immutable.IndexedSeq`. – Jesper Jul 28 '10 at 08:10