0

I have tried below array example in my scala console.Declared immutable array, tried to change the array index values.Immutable should not allow modifying the values. I don't understand whats happening .can anyone explain, please.

val numbers=Array(1,2,3)
numbers(0)=5
print numbers
res1: Array[Int] = Array(5, 2, 3)

Thanks!

2

3 Answers 3

3

Declaring something as a val does not make it immutable. It merely prevents reassignment. For example, the following code would not compile:

val numbers = Array(1, 2, 3)
numbers = Array(5, 2, 3)

Notice that what changes in the above code is not something about the array object's internal state: what changes is the array that the name numbers references. At the first line, the name numbers refers to the array Array(1, 2, 3), but in the second line we try reassign the name numbers to the array Array(5, 2, 3) (which the compiler won't allow, since the name numbers is declared using val).

In contrast, the below code is allowed:

val numbers = Array(1, 2, 3)
numbers(0) = 5

In this code, the name numbers still points to the same array, but it's the internal state of the array that has changed. Using the val keyword for the name of an object cannot prevent that object's internal state from changing, the val keyword can only prevent the name from being reassigned to some other object.

Sign up to request clarification or add additional context in comments.

Comments

2

You did not declare an immutable array. Array in Scala is mutable.

Where you might be confused is what exactly val vs var means. val does not make an object immutable, it makes the reference immutable so you can't reassign a different array to your variable, but you can still modify the contents since it is a mutable object.

If you want immutability you need to use val together with an immutable object like Vector or List.

Comments

0

Maybe your understanding of scala Array is not right.

Please pay attention to the following principle!

Arrays preserve order, can contain duplicates, and are mutable.

scala> val numbers = Array(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
numbers: Array[Int] = Array(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

scala> numbers(3) = 10

Lists preserve order, can contain duplicates, and are immutable.

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

scala> numbers(3) = 10
<console>:9: error: value update is not a member of List[Int]
              numbers(3) = 10

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.