Skip to main content

Platforms and Technology

Scala: Immutable data structure

immutable_image

Scala, a programming language that combines object-oriented and functional programming paradigms, provides a variety of immutable data structures. Immutable data structures are those that cannot be modified after they are created, which can be beneficial for ensuring safety and simplicity in concurrent or parallel programming. Here are some commonly used immutable data structures in Scala:

  • List
  • Set
  • Map
  • Tuple
  • Vector
  • Range

Let’s explore some immutable data structures.

  1. List:

List is an ordered, immutable collection of elements of the same type. It represents a linked list data structure.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valimmutableList=List(1, 2, 3)
val immutableList = List(1, 2, 3)
val immutableList = List(1, 2, 3)

In the example, immutableList is created with three elements: 1, 2, and 3. Once a list is created, its elements cannot be modified. Any operation that seems to modify the list returns a new list.

Common Operations on Immutable Lists:

  • Accessing Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valfirstElement= immutableList.head // 1
valrestOfTheList= immutableList.tail // List(2, 3)
val firstElement = immutableList.head // 1 val restOfTheList = immutableList.tail // List(2, 3)
val firstElement = immutableList.head // 1
val restOfTheList = immutableList.tail // List(2, 3)
  • Prepending and Appending:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valnewList=0 +: immutableList // List(0, 1, 2, 3)
valanotherList= immutableList :+ 4// List(1, 2, 3, 4)
val newList = 0 +: immutableList // List(0, 1, 2, 3) val anotherList = immutableList :+ 4 // List(1, 2, 3, 4)
val newList = 0 +: immutableList // List(0, 1, 2, 3)
val anotherList = immutableList :+ 4 // List(1, 2, 3, 4)
  • Concatenation:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valcombinedList= immutableList ++ List(4, 5)// List(1, 2, 3, 4, 5)
val combinedList = immutableList ++ List(4, 5) // List(1, 2, 3, 4, 5)
val combinedList = immutableList ++ List(4, 5) // List(1, 2, 3, 4, 5)
  • Filtering and Mapping:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valevenNumbers= immutableList.filter(_ % 2 == 0)// List(2)
valsquaredList= immutableList.map(x => x * x)// List(1, 4, 9)
val evenNumbers = immutableList.filter(_ % 2 == 0) // List(2) val squaredList = immutableList.map(x => x * x) // List(1, 4, 9)
val evenNumbers = immutableList.filter(_ % 2 == 0) // List(2)
val squaredList = immutableList.map(x => x * x) // List(1, 4, 9)

Immutable lists in Scala provide a convenient and safe way to work with sequences of elements. The immutability ensures that operations on lists do not modify the original list, promoting functional programming principles. This is particularly advantageous in concurrent and parallel programming, as it reduces the risk of shared mutable state issues. While mutable lists exist in Scala (scala.collection.mutable.ListBuffer), the use of immutable lists is generally preferred for reasons of clarity, predictability, and thread safety.

  1. Set:

Set is an immutable collection in Scala that represents an unordered collection of unique elements. It does not allow duplicate elements.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valimmutableSet=Set(1, 2, 3)
val immutableSet = Set(1, 2, 3)
val immutableSet = Set(1, 2, 3)

In the example, immutableSet is created with three elements: 1, 2, and 3. Once a set is created, it cannot be modified. Operations on the set return a new set.

Common Operations on Immutable Sets:

  • Adding and Removing Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valnewSet= immutableSet + 4// Set(1, 2, 3, 4)
valanotherSet= immutableSet - 2// Set(1, 3)
val newSet = immutableSet + 4 // Set(1, 2, 3, 4) val anotherSet = immutableSet - 2 // Set(1, 3)
val newSet = immutableSet + 4 // Set(1, 2, 3, 4)
val anotherSet = immutableSet - 2 // Set(1, 3)
  • Union, Intersection, and Difference:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valcombinedSet= immutableSet ++ Set(3, 4, 5)// Set(1, 2, 3, 4, 5)
valcommonElements= immutableSet.intersect(Set(2, 3, 4))// Set(2, 3)
valdifferenceSet= immutableSet.diff(Set(2, 3))// Set(1)
val combinedSet = immutableSet ++ Set(3, 4, 5) // Set(1, 2, 3, 4, 5) val commonElements = immutableSet.intersect(Set(2, 3, 4)) // Set(2, 3) val differenceSet = immutableSet.diff(Set(2, 3)) // Set(1)
val combinedSet = immutableSet ++ Set(3, 4, 5) // Set(1, 2, 3, 4, 5)
val commonElements = immutableSet.intersect(Set(2, 3, 4)) // Set(2, 3)
val differenceSet = immutableSet.diff(Set(2, 3)) // Set(1)
  • Checking Membership:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valcontainsTwo= immutableSet.contains(2)// true
val containsTwo = immutableSet.contains(2) // true
val containsTwo = immutableSet.contains(2) // true

Immutable sets in Scala provide a way to work with unique elements in a collection without allowing duplicates. The immutability ensures that any operation on a set creates a new set, which is beneficial for functional programming. Immutable sets are thread-safe and suitable for concurrent and parallel programming, as there are no risks associated with shared mutable state. While mutable sets (scala.collection.mutable.Set) exist in Scala, using immutable sets is generally recommended for their safety and adherence to functional programming principles.

  1. Map:

Map is an immutable collection in Scala that represents a collection of key-value pairs. Each key is associated with exactly one value, and keys are unique within the map.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valimmutableMap=Map("one" ->1, "two" ->2, "three" ->3)
val immutableMap = Map("one" -> 1, "two" -> 2, "three" -> 3)
val immutableMap = Map("one" -> 1, "two" -> 2, "three" -> 3)

In the example, immutableMap is created with three key-value pairs. Once a map is created, it cannot be modified. Operations on the map return a new map.

Common Operations on Immutable Maps:

  • Accessing Values:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valvalueForTwo=immutableMap("two")// 2
val valueForTwo = immutableMap("two") // 2
val valueForTwo = immutableMap("two") // 2
  • Adding and Removing Entries:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valnewMap= immutableMap + ("four" ->4)// Map("one" -> 1, "two" -> 2, "three" -> 3, "four" -> 4)
valanotherMap= immutableMap - "two"// Map("one" -> 1, "three" -> 3)
val newMap = immutableMap + ("four" -> 4) // Map("one" -> 1, "two" -> 2, "three" -> 3, "four" -> 4) val anotherMap = immutableMap - "two" // Map("one" -> 1, "three" -> 3)
val newMap = immutableMap + ("four" -> 4) // Map("one" -> 1, "two" -> 2, "three" -> 3, "four" -> 4)
val anotherMap = immutableMap - "two" // Map("one" -> 1, "three" -> 3)
  • Merging Maps:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valmergedMap= immutableMap ++ Map("three" ->33, "four" ->4)// Map("one" -> 1, "two" -> 2, "three" -> 33, "four" -> 4)
val mergedMap = immutableMap ++ Map("three" -> 33, "four" -> 4) // Map("one" -> 1, "two" -> 2, "three" -> 33, "four" -> 4)
val mergedMap = immutableMap ++ Map("three" -> 33, "four" -> 4) // Map("one" -> 1, "two" -> 2, "three" -> 33, "four" -> 4)
  • Checking Key Existence:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valcontainsTwoKey= immutableMap.contains("two")// true
val containsTwoKey = immutableMap.contains("two") // true
val containsTwoKey = immutableMap.contains("two") // true

Immutable maps in Scala provide a convenient way to represent associations between keys and values. The immutability ensures that operations on maps do not modify the original map, aligning with functional programming principles. Immutable maps are safe for concurrent and parallel programming, reducing the risk of shared mutable state. While mutable maps (scala.collection.mutable.Map) exist, using immutable maps is generally recommended for clarity, predictability, and thread safety in functional programming contexts.

Immutable Collections (from scala.collection.immutable package):

Scala provides various other immutable collections like Queue, Stack, LinkedList, etc.

References:

Here are the Spark documents delving further into the creation of immutable data structures in Scala.

Official Spark Documentation:
https://spark.apache.org/docs/latest/api/scala/scala/index.html
https://docs.scala-lang.org/overviews/collections/overview.html

In conclusion, Immutable data structures in Scala play a crucial role in functional programming by promoting immutability, referential transparency, and thread safety. The immutability guarantees that operations on these structures do not modify the existing instances but instead create new ones. This helps in writing code that is less error-prone, easier to reason about, and safer in concurrent or parallel environments. It also aligns with the principles of functional programming, where avoiding mutable state is a key concept.

Tags

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Saranya Sridhar

Saranya is an Technical Consultant at Perficient, exploring the stages of Big Data. Her experience includes Spark, Scala, SQL, Databricks, Java, and BI tools like Tableau, Spotfire, and Power BI. She passionately delves into emerging technologies.

More from this Author

Follow Us