0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Immutability and Side Effects

Understand the importance of immutability in functional programming and how to manage side effects effectively.

Immutable by Design

Welcome to our lesson on Immutability and Side Effects! These are core concepts in functional programming (FP) that help us write cleaner, more predictable code.

In FP, we prefer to work with immutable data. This means once a piece of data is created, it cannot be changed. Think of it like a photograph – you can look at it, but you can't alter the original moment it captured.

val vs. var in Scala

Scala makes it easy to declare immutable values using the val keyword. This is a constant reference that cannot be reassigned after its initial definition. For mutable variables, you'd use var.

Let's see the difference:

object Main {
  def main(args: Array[String]): Unit = {
    // Immutable value
    val greeting = "Hello"
    // greeting = "Hi" // This would cause a compile error!

    // Mutable variable
    var count = 0
    count = 1 // This is allowed

    println(greeting)
    println(count)
  }
}

All lessons in this course

  1. Functions as First-Class Values
  2. Higher-Order Functions & Currying
  3. Immutability and Side Effects
← Back to Scala for Backend Engineering & Functional Programming