Scala scala.util.Sorting.quickSort is changing the value of an array?
Scala scala.util.Sorting.quickSort is changing the value of an array?
I was reading on the book "Scala for the Impatient"
On Chapter 3, it comes across this code
val a = Array(1, 7, 2, 9)
scala.util.Sorting.quickSort(a)
// a is now Array(1, 2, 7, 9)
I thought val a should be immutable in scala? What is going on here?
val a
1 Answer
1
The code doesn't change the binding of a. It mutates the object that a references. a still points to the same object as it did before, only the internal state of that object has changed.
a
a
a
The documentation says that the array is sorted in-place (bold emphasis mine):
def quickSort[K](a: Array[K])(implicit arg0: math.Ordering[K]): Unit
def quickSort[K](a: Array[K])(implicit arg0: math.Ordering[K]): Unit
Sort array a with quicksort, using the Ordering on its elements. This algorithm sorts in place, so no additional memory is used aside from what might be required to box individual elements during comparison.
a
Hmm.. so when it says
a is immutable, it just means the pointer of a is not changed? But the internal state of a can be changed? I thought every object in Scala cannot has its state or value changed, thus immutable.– Man-Kit Yau
Sep 1 at 8:56
a
a
a
That is not true. Scala is an object-oriented language. Any object can decide how to handle its own internal state. Most Scala programmers elect to write immutable objects, but they don't have to. There is an entire package full of mutable types in
scala.collections.mutable, for example. Also, Scala is designed to be hosted on a language platform (e.g. JVM, CLI, ECMAScript) that may support mutable objects. In particular, if you run your code on Scala-JVM, then the array will actually be a Java array, and those most certainly are mutable, Scala cannot magically change that fact.– Jörg W Mittag
Sep 1 at 8:59
scala.collections.mutable
Ok, thank you so much @Jörg W Mittag
– Man-Kit Yau
Sep 1 at 9:01
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Possible duplicate of mutable vs. immutable in Scala collections
– Ben
Sep 1 at 12:55