Title: Scala scala.util.Sorting.quickSort is changing the value of an array?
Tags: arrays;scala
Question: 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?
Comment: Possible duplicate of [mutable vs. immutable in Scala collections](https://stackoverflow.com/questions/8287425/mutable-vs-immutable-in-scala-collections)

Here is the accepted answer: 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.
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
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.
Comment for this answer: 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.
Comment for this answer: 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.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:09/01/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<arrays><scala>', 'Title': 'Scala scala.util.Sorting.quickSort is changing the value of an array?', 'ViewCount': 72, 'id': 52126485, 'user_AboutMe': None, 'user_AccountId': 10462878.0, 'user_DisplayName': 'Man-Kit Yau', 'user_Reputation': 149.0, 'user_Views': 26.0, 'user_id': 7713078.0}}