There are several immutable collection classes in Scala. They are different in their implementation of maps, sets, and sequences. The collection classes are as follows:
Let’s cover some important immutable collection classes in this shot.
Lists are finite sized sequences. Lists offer O(1) accessibility. Most operations in a list like adding an element, removing an element are O(n) complexity.
A LazyList is similar to a List. Only difference is that the elements and methods are computer lazily.
By lazily, it means that all elements are constructed only as a proxy of resultant collection.
The elements are constructed whenever they are demanded. This means that a lazylist can be infinitely long.
Let’s look at the code:
scala> val lazyList = 1 #:: 2 #:: 3 #:: LazyList.empty lazyList: scala.collection.immutable.LazyList[Int] = LazyList(<not computed>)
In order to create a lazy list, use the
ArraySeq does not cater to the head of the collection to modify random elements from it. In lists, it is inefficient to access random locations.
ArraySeqs can easily access elements at any location in a constant time O(1).
Let’s have a look at the syntax:
// create an array scala> val arr1 = scala.collection.immutable.ArraySeq(1, 2, 3) // append an element scala> val arr2 = arr1 :+ 10 arr2: scala.collection.immutable.ArraySeq[Int] = ArraySeq(1, 2, 3, 10)
Since ArraySeqs are immutable, the updated, appended and prepended operations create new
Vectors are one the most widely used collections in Scala. Unlike ArraySeq and Lists, vectors provide good performance for prepending and appending an element. Vectors have the ability to access elements in “effectively” constant time O(1).
Also, vectors provide easy modifications at any arbitrary location. Let’s see how to write the code for vectors:
// creating empty vector scala> val vect1 = scala.collection.immutable.Vector.empty appending scala> val vec2 = vec1 :+ 3 :+ 4 vec2: scala.collection.immutable.Vector[Int] = Vector(3, 4)
A queue is a FIFO (First in first out) based collection of data. Key operations include
enqueue which involves adding a new element at the end of the queue, and
dequeue which removes the element at the front of the queue.
// Creating an empty queue scala> val empty = scala.collection.immutable.Queue[Int]() // enqueue/add an element scala> val queue1 = empty.enqueue(1) // Removing an element scala> queue2 = queue1.dequeue
A Range refers to an ordered sequence of data like “1, 2, 3”, “10, 20, 30” etc. In Scala, ranges are easily defined using the start value, end value, and the stepping value. To define the range, the keywords
by are used.
scala> 1 to 3 res2: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3) scala> 10 to 40 by 10 res3: scala.collection.immutable.Range = Range(10, 20, 30, 40)
You can use
until to keep the range below the upper limit.
scala> 1 until 3 res2: scala.collection.immutable.Range = Range(1, 2)
View all Courses