
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Methods
- Scala - Functions
- Scala - Methods vs Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala - Polymorphic Functions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - NumericRange
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala Advanced Types
- Scala - Union Types
- Scala - Intersection Types
- Scala - Type Aliases
- Scala - Structural Types
- Scala - Match Expression
- Scala - Singleton Type Operator
- Scala - Abstract Types
- Scala - Dependent Types
- Scala - Abstract Type Bounds
- Scala - Higher-Kinded Types
- Scala - Opaque Type Alias
- Scala - Path-Dependent Types
- Scala - Type Lambdas
- Scala - Type Inference
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Guards
- Scala - Variables in Patterns
- Scala - Type Patterns
- Scala - The Matchable Trait
- Scala - Matching Arrays
- Scala - Matching Lists
- Scala - Matching Tuples
- Scala - Exception Handling
- Scala - Extractors
- Scala - Pattern Bindings
- Scala - Regular Expressions
- Scala - Case Classes
- Scala - Partial Functions
- Scala - Packaging and Imports
- Scala - Implicit Imports
- Scala - Export Clauses
- Scala - Nested Packages
- Scala - Chained Packages
- Scala - Package Objects
- Scala Files I/O
- Scala - Files I/O
- Scala - Writing Files
- Scala - Listing Files
- Scala - Deleting Directories
- Scala - Check File Exists
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Process Management
- Scala - Scaladoc
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala Unit Testing
- Scala - Unit Testing
- Scala - uTest
- Scala - MUnit
- Scala - ScalaTest Runner
- Scala - ScalaMock
- Scala - JUnit
- Scala - Mocking
- Scala - BDD Testing
Scala - Mutable and Immutable Collections
Scala has a collection library that is located under the scala.collection package. Collections in Scala are basics to store, retrieve, and manipulate groups of objects efficiently. There are types of collections: mutable and immutable. We will explain both of these in this chapter.
Mutable Collections
You can update and modify immutable type collections even after declaring these. You can update mutable collections in-place, so it will not require you to create other collections for these updates. You update mutable collections in-place. Mutable collections are located at scala.collection.mutable. So you will need to import this library when you work on immutable collections. Mutable collections are used when you need to frequently update the collection.
Examples are: ListBuffer, HashSet, HashMap, ArrayBuffer, Queue, Stack.
Declaring Mutable Collections
The following is the syntax for declaring various mutable collections in Scala -
Syntax
import scala.collection.mutable.ListBuffer import scala.collection.mutable.HashSet import scala.collection.mutable.HashMap val mutableList: ListBuffer[String] = ListBuffer("Apple", "Banana", "Cherry") val mutableSet: HashSet[String] = HashSet("Apple", "Banana", "Cherry") val mutableMap: HashMap[String, String] = HashMap ("red" -> "#FF0000", "green" -> "#00FF00", "blue" -> "#0000FF")
Note that it is necessary to import their library otherwise it will not compile.
Example
Below is an example program showing how to create, initialize, and process mutable collections
import scala.collection.mutable.ListBuffer import scala.collection.mutable.HashSet import scala.collection.mutable.HashMap object Demo { def main(args: Array[String]) = { val mutableList: ListBuffer[String] = ListBuffer("Apple", "Banana", "Cherry") val mutableSet: HashSet[String] = HashSet("Apple", "Banana", "Cherry") val mutableMap: HashMap[String, String] = HashMap ("red" -> "#FF0000", "green" -> "#00FF00", "blue" -> "#0000FF") // Print the collections println(mutableList) println(mutableSet) println(mutableMap) // Modify the collections (in-place) mutableList += "Grapes" mutableSet += "Grapes" mutableMap += ("yellow" -> "#FFFF00") // Print the modified collections println(mutableList) println(mutableSet) println(mutableMap) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
ListBuffer(Apple, Banana, Cherry) Set(Apple, Banana, Cherry) Map(red -> #FF0000, green -> #00FF00, blue -> #0000FF) ListBuffer(Apple, Banana, Cherry, Grapes) Set(Apple, Banana, Cherry, Grapes) Map(red -> #FF0000, green -> #00FF00, blue -> #0000FF, yellow -> #FFFF00)
Immutable Collections
You cannot update and modify immutable type collections once you create these. If you try to add, remove, and update immutable collections then the compiler will return a new collection. The original collection will remain the same. Immutable collections are located at scala.collection.immutable. So you will need to import this library when you work on immutable collections.
Examples are: List, Set, Map, Vector, Queue, Stack, Range, Option, Tuple, Iterator.
Declaring Immutable Collections
The following is the syntax for declaring various immutable collections in Scala -
Syntax
import scala.collection.immutable.List import scala.collection.immutable.Set import scala.collection.immutable.Map val immutableList: List[String] = List("Apple", "Banana", "Cherry") val immutableSet: Set[String] = Set("Apple", "Banana", "Cherry") val immutableMap: Map[String, String] = Map ("red" -> "#FF0000", "green" -> "#00FF00", "blue" -> "#0000FF")
Since these are immutable by default, so even if you do not import their immutable collection library then it will also work, like this -
val immutableList: List[String] = List("Apple", "Banana", "Cherry") val immutableSet: Set[String] = Set("Apple", "Banana", "Cherry") val immutableMap: Map[String, String] = Map ("red" -> "#FF0000", "green" -> "#00FF00", "blue" -> "#0000FF")
Example
object Demo { def main(args: Array[String]) = { val immutableList: List[String] = List("Apple", "Banana", "Cherry") val immutableSet: Set[String] = Set("Apple", "Banana", "Cherry") val immutableMap: Map[String, String] = Map ("red" -> "#FF0000", "green" -> "#00FF00", "blue" -> "#0000FF") // Print the collections println(immutableList) println(immutableSet) println(immutableMap) // Attempt to modify collections (will return new collections) val newList = immutableList :+ "Grapes" val newSet = immutableSet + "Grapes" val newMap = immutableMap + ("yellow" -> "#FFFF00") // Print the new collections println(newList) println(newSet) println(newMap) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
List(Apple, Banana, Cherry) Set(Apple, Banana, Cherry) Map(red -> #FF0000, green -> #00FF00, blue -> #0000FF) List(Apple, Banana, Cherry, Grapes) Set(Apple, Banana, Cherry, Grapes) Map(red -> #FF0000, green -> #00FF00, blue -> #0000FF, yellow -> #FFFF00)
Difference between Mutable and Immutable Collections
Feature | Mutable Collections | Immutable Collections |
---|---|---|
Modifiability | Can be modified after creation. | Cannot be modified after creation. |
Thread-safety | Not inherently thread-safe. | Inherently thread-safe. |
Performance | Better for frequent updates and large data sets. | Better for functional programming and thread-safe operations. |
Memory Consumption | May use more memory due to potential internal reallocation. | Generally uses less memory as the structure is not modified. |
Common Use Cases | Real-time data processing, performance-critical applications. | Functional programming, concurrent applications. |
Examples | ListBuffer, HashSet, HashMap, ArrayBuffer, Queue, Stack | List, Set, Map, Vector, Queue, Stack, Range, Option, Tuple, Iterator |