Scala mutable and immutable collections

 228 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala mutable and immutable collections.

What is a collection?

The collection is a data structure which is used to hold a group of objects. It is mainly used for storing data and doing some operations on the collection. Example addition of new object, removal, update and retrieve data for further processing.

Collection is an important feature of programming language

Scala collections are generally divided into two types. Mutable and immutable collection

Scala Mutable collection

Mutable collection can be modified. We can add data, remove a data, or update a data. But every change will modify the collection itself. As a side effect, every change will affect the collection itself.

In Scala , to use a mutable collection ,below package has to be imported

import scala.collection.mutable

Example of mutable Set

import scala.collection.mutable
object Myscala {
  def main(args: Array[String]) {
    val set = mutable.Set(1, 2, 3);
    set += 4; //adding 4
    set += 5; //adding 5
    set -= 1; //removing 1
    set -= 2; //removing 2
    set.foreach(println); //Expected output is 5,3,4
  }
}

Output

5
3
4

Scala Immutable collection

Every change in an immutable collection will create a new collection and the original collection will not be modified. We can add data, remove a data, or update a data. But every change will create a new collection.

No import is required. By default, immutable collection will be imported and used.

Example

object Myscala {
  def main(args: Array[String]) {
    val set = Set(1, 2, 3);
    set + 4; //adding 4
    set + 5; //adding 5
    set - 1; //removing 1
    set - 2; //removing 2
    set.foreach(println); //Expected output is 1,2,3
  }
}

Output

1
2
3

If you notice the above example, addition and removal haven’t modified the original collection. Each change has to be captured or stored in a new collection.

Note: To use a mutable collection, we have to explicitly import scala.collection.mutable

These are the main differences of Scala mutable and immutable collections.

Reference : Official documentation

Hope this article helped you 🙂 Please leave a comment and give us a thumbs up!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.