views:

98

answers:

1

Hi

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 ??

Cheers

+6  A: 

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
thanks Elmo.. So "object to which it refers could potentially still be changed" only applicable for arrays declared with val(immutable).... ??
Ramesh Vel
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
thanks Elmo.. i just started reading List.. :)
Ramesh Vel
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
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