Question about Scala variable mutability

I understand that the val keyword defines an underlying variable of type Immutable (cannot be reassigned later). Now I come across a paragraph in programming in scala (Chapter 3, Next steps in scala - parameterizing 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 the important concept of understanding about scala regarding shaft meanings. When you define a variable with val, the variable can not be reassigned, but the object to which it refers can potentially be changed. So in this case you could not reassign greetStrings to another array; greetStrings will always point to the same Array [String] array with which it was initialized. But you can change the elements of this array [String] over time, so the array itself is mutable.

therefore, it is valid for modifying array elements. And its invalid if we define it as

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

It satisfies the statement below.

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

but if I declare something like this

 val str = "immutable string" 

By definition given in the book

which means the object to which it relates can potentially be modified in the above line of code

+4
source share
1 answer

The val declaration does not guarantee or even imply an immutable type. It only declares what you could call the final variable in Java. The identifier cannot be reassigned, but the value can be of a mutable type.

In your example string value, you have both val and immutable String type. Thus, this identifier is not reassignable or mutable (immutable).

+10
source

All Articles