Working with Collections in Scala

March 23, 2024

Here, we cover the powerful collection framework in Scala, including lists, arrays, maps, and sets. We explore common operations on collections, such as mapping, filtering, and reducing, and discuss the immutability and functional aspects of Scala collections.

Lists, Arrays, Maps, and Sets

In Scala, collections are an essential part of the language. There are several collection types, including lists, arrays, maps, and sets, each with its own unique characteristics and use cases.

Lists

A list in Scala is an ordered collection of elements of the same type. Lists are immutable, meaning elements cannot be added, removed, or changed after the list is created. To create a list, you can use the List class:

val numbers = List(1, 2, 3, 4, 5)

You can perform various operations on lists, such as head to get the first element, tail to get the rest of the elements, and filter to select elements that satisfy a predicate.

Arrays

Arrays in Scala are mutable, meaning you can modify the elements after the array is created. To create an array, you can use the Array class:

val colors = Array("red", "green", "blue")

Arrays also support common operations such as map to transform elements and foreach to iterate over elements.

Maps

A map in Scala is a collection of key-value pairs. Maps are immutable by default, but you can use the mutable.Map class for mutable maps:

val ages = Map("Alice" -> 25, "Bob" -> 30, "Carol" -> 35)

You can access values in a map using the key, add new key-value pairs, and perform operations such as keys and values.

Sets

Sets in Scala are collections of unique elements with no duplicates. Sets are immutable and can be created using the Set class:

val vowels = Set("a", "e", "i", "o", "u")

Common operations on sets include union to combine two sets, intersect to find common elements, and diff to find elements present in one set but not the other.

Common Operations on Collections

Scala provides a rich set of operations for working with collections, many of which are inspired by functional programming concepts. Some of the common operations include:

  • Mapping: Transforming each element in a collection using a function.
  • Filtering: Selecting elements from a collection that satisfy a predicate.
  • Reducing: Combining elements in a collection to produce a single result.

Immutability and Functional Aspects

One of the key features of Scala collections is immutability. Immutable collections ensure that once created, their contents cannot be changed, which promotes safety and predictability in code. Additionally, Scala’s collections library embraces functional programming principles, making it easy to write concise and expressive code when working with collections.