In “Programming in scala” it is stated that lists are immutable and arrays are mutable. But I can’t change the array length — neither can I with list, so in this way they are both immutable. I can change array’s element value — just setting a new one, and I can modify a list’s element value with, say, map method. So in this way they are both mutable.
So why arrays are considered to be mutable and lists not?
First, it’s important to know that Scala actually has both mutable and immutable collections. If you use
scala.collection.mutable.ListBuffer, it will (as the name indicates) be mutable. If you usescala.collection.immutable.Listit will not be.Second, the
mapfunction does not alter the elements of the list, rather, it creates an entirely new list containing the result of the map function applied to each element of the start list, for example:l2now contains a new list, entirely separate froml1, andl1has not been changed.