0

As the documentation states, List should be immutable: https://www.scala-lang.org/api/2.12.17/scala/collection/immutable/List.html and https://docs.scala-lang.org/overviews/collections/concrete-immutable-collection-classes.html

However, this piece of codes does work (source: Udemy Apache Spark with Scala course...):

var numList = List[Int]()
for (num <- 1 to 20) {
  numList = numList ++ List(num)
}

Does this mean List can be defined as a mutable variable? Thanks!


Edit: This question is closed saying it's been answered here: What is the difference between a var and val definition in Scala? But they are two different questions. What @Mateusz Kubuszok answered in the comment is right - Whether reference is mutable (var and val) is independent of whether the inner structure is mutable. I wish I could select that as the right answer but it looks like I cannot do that...

Francisca
  • 3
  • 2
  • There are two ways of declaring variables in scala. ```val mySampleConstant``` and ```var myVariable```. So in your case you are using the not recommended way with var and thats why is mutable. Replace var with val and check again. – Alex Karamfilov Oct 20 '22 at 06:29
  • Scala have both mutable and immutable Lists but you are mutating the reference to immutable structure. At every "iteration" of for you'll have a different reference at `numList` while with mutable.MutableList you could have the same reference with a different content (if you haven't used `var`). Whether reference is mutable (var and val) is independent of whether the inner structure is mutable. – Mateusz Kubuszok Oct 20 '22 at 12:44

0 Answers0