7

I'm starting to play with Scala, and one of the first things I read is that vals are:

variables that are assigned once and never change, and vars, variables that may change over their lifetime

But I'm curious why I can do this:

val foo = Array(1, 3 ,2)
scala.util.Sorting.quickSort(foo)

If I check the foo variable now is ordered, which means it has changed... also if I do print(foo), both have the same, so the variable is pointing to the same object (I could have thought that the variable just pointed to a new object)

Could anyone clarify?

jasalguero
  • 4,142
  • 2
  • 31
  • 52

2 Answers2

15

The Array pointed to by the foo variable is changing, but the fact that foo points at that Array doesn't change. Try re-assigning foo and you will see what you are looking for.

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
3

The problem is not with val, but with Array. Although values are unchangeable, arrays are. If you are looking to stop this, you can use a class within the package immutable.