1

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?

Man-Kit Yau
  • 149
  • 1
  • 10
  • Possible duplicate of [mutable vs. immutable in Scala collections](https://stackoverflow.com/questions/8287425/mutable-vs-immutable-in-scala-collections) – Ben Sep 01 '18 at 12:55

1 Answers1

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.

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.

Community
  • 1
  • 1
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 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 01 '18 at 08:56
  • 1
    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 01 '18 at 08:59