Scala Lesson 13 – Immutability | Dataplexa

Immutability in Scala

In this lesson, you will learn about immutability, one of the most important core principles of Scala and functional programming.

Immutability means that once a value or object is created, it cannot be changed. Instead of modifying data, Scala encourages creating new data with updated values.


What Is Immutability?

An immutable object is an object whose state cannot be modified after it is created. If you want a different value, you create a new object instead of changing the existing one.

Scala promotes immutability by default, which helps in writing safer and more predictable code.


Immutable Variables in Scala

In Scala, variables declared using val are immutable. Once assigned, their value cannot be changed.

val x = 10
// x = 20   // This will cause a compilation error

Trying to reassign a val results in a compile-time error.


Mutable Variables Using var

Variables declared using var are mutable and can be reassigned. However, their use is discouraged unless absolutely necessary.

var count = 5
count = 10
println(count)

Using var makes code harder to reason about and more error-prone.


Immutable Collections

Scala’s standard collections such as List, Set, and Map are immutable by default.

Operations on immutable collections always return a new collection.


Example: Immutable List

val numbers = List(1, 2, 3)
val newNumbers = numbers :+ 4

println(numbers)
println(newNumbers)

The original list remains unchanged, while a new list is created.


Example: Immutable Set

val data = Set(1, 2, 3)
val updatedData = data + 4

println(data)
println(updatedData)

The original set is preserved and a new set is returned.


Example: Immutable Map

val scores = Map("Alice" -> 90, "Bob" -> 85)
val newScores = scores + ("Charlie" -> 88)

println(scores)
println(newScores)

Why Immutability Matters

Immutability provides several advantages:

  • Prevents accidental data modification
  • Makes code easier to understand
  • Improves thread safety
  • Works well with concurrency

Because immutable objects never change, multiple threads can safely share them.


Immutability and Functions

Functions in Scala typically avoid modifying external state. Instead, they return new values.

def addOne(x: Int): Int = {
  x + 1
}

println(addOne(5))

This function does not change any variable; it simply returns a new value.


Immutability vs Mutability

Understanding when to use immutability helps you write better Scala programs.

  • Prefer val over var
  • Prefer immutable collections
  • Use mutation only when performance truly requires it

Real-World Use of Immutability

Immutability is widely used in:

  • Functional programming
  • Concurrent systems
  • Big data processing
  • Distributed applications

Most modern Scala frameworks rely heavily on immutable data structures.


📝 Practice Exercises


Exercise 1

Create an immutable list and add a new element to it.

Exercise 2

Create an immutable map and update one key-value pair.

Exercise 3

Write a function that returns the square of a number without modifying any variable.


✅ Practice Answers


Answer 1

val items = List(10, 20, 30)
val updatedItems = items :+ 40
println(updatedItems)

Answer 2

val prices = Map("Pen" -> 10, "Book" -> 50)
val newPrices = prices + ("Pen" -> 12)
println(newPrices)

Answer 3

def square(n: Int): Int = n * n
println(square(6))

What’s Next?

In the next lesson, you will learn about Options in Scala, which help you handle missing or optional values safely.