Scala collections
In the previous section, we saw how to create the List and Set structures in Scala in an immutable way. Now we will learn to work with the List and Set structures in a mutable way, and also with other collections such as sequences, tuples, and Maps. Let's take a look at the Scala collections hierarchy tree, as shown in the following diagram:
Now let's take a look at the Scala Seq class hierarchy. As you can see, Seq is traversable as well.
Scala collections extend from traversable, which is the main trait of all collection's descends. List structures, for instance, extend from Seq class hierarchy, which means sequence - List is a kind of sequence. All these trees are immutable or mutable depending on the Scala package you end up using.
Let's see how to perform basic mutable operations with List structures in Scala. In order to have filter and removal operations, we need use a Buffer sequence as follows:
$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala>var ms = scala.collection.mutable.ListBuffer(1,2,3)
ms: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)
scala>ms += 4
res0: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4) scala>ms += 5
res1: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5) scala>ms += 6
res2: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5, 6) scala>ms(1) res3: Int = 2 scala>ms(5) res4: Int = 6 scala>ms -= 5
res5: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 6) scala>ms -= 6
res6: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4) scala>
Let's see the next set of code.