Scala vals can be changed

I start playing with Scala, and one of the first things I read is that vals:

which are assigned once and never change, and variables that may change throughout their lives

But I'm curious why I can do this:

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

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

Can anyone clarify?

+6
source share
2 answers

The array pointed to by the variable foo is changing, but the fact that foo indicates that Array not changing. Try reassigning foo and you will see what you are looking for.

+14
source

The problem is not val, but Array. Although the values ​​are immutable, arrays. If you want to stop this, you can use the class inside the package unchanged.

+3
source

Source: https://habr.com/ru/post/905327/


All Articles