Let us see mutable and immutable collections.
As we have seen earlier
- Traversable is the base trait with abstract method foreach and many other concrete methods to manipulate collections
- foreach is implemented in sub trait Iterable
- Iterable have abstract method iterator
- Iterable have 3 sub traits Seq, Set and Map
- All the concrete classes under Seq, Set and Map are either mutable and immutable
- scala.collection is the base package
- It has sub packages scala.collection.immutable and scala.collection.mutable
- There are some concrete classes under scala.collection as well. They are immutable
- List is immutable and Array is mutable. While List is Seq class, Array is special type of Scala collection analogous to Java Array.
- immutable means we will not be able to update elements of collection, mutable means elements can be updated in place.
- mutable collections have method called update
- update can be invoked like this as well –
val a = Array(1, 2, 3); a(0) = 4
- This will not work for List as it is immutable, even if you define collection as mutable using var
Here is the official documentation – http://docs.scala-lang.org/overviews/collections/overview