Overview of Scala Collections: Mutable and Immutable Types with Examples
This article introduces Scala's collection library, explaining the distinction between mutable and immutable collections and detailing common types such as List, Set, Map, Tuple, Option, and Iterator, accompanied by example code for each.
Scala provides a robust collection framework that includes both mutable and immutable collections.
Mutable collections can be updated or expanded, allowing elements to be added, removed, or modified, while immutable collections never change; operations on them return new collections, leaving the original unchanged.
The most commonly used collection types are:
List : an ordered, linear collection that may contain duplicate elements.
Set : an unordered collection that contains no duplicate elements.
Map : a collection of key‑value pairs, where each key maps to a value.
Tuple : a fixed‑size collection that can hold elements of different types.
Option : a container that may hold a value of a given type or be empty.
Iterator : not a container but a way to access elements of a collection sequentially.
Example definitions for each collection type are shown below:
// Define an integer List
val x = List(1,2,3,4) // Define a Set
val x = Set(1,3,5,7) // Define a Map
val x = Map("one" -> 1, "two" -> 2, "three" -> 3) // Create a Tuple with two different types
val x = (10, "Runoob") // Define an Option
val x: Option[Int] = Some(5)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
