Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Functional Programming

Immutability and Pure Functions in Scala

Understand functional programming in Scala: immutable values, pure functions, referential transparency, side effects, recursion and tail recursion with @tailrec.

Scala lets you write in an object-oriented style, a functional style, or a mix. The functional style is what most Scala teams aim for in the core of their programs, because it makes code easier to test, reason about and run in parallel. It rests on two simple ideas: prefer immutable data and write pure functions.

You have already met the first idea: case classes are immutable and copy makes changed versions. This lesson explains why that matters and introduces the second idea.

val, var and immutable collections

val creates a name that cannot be reassigned; var can be. In functional code you use val almost exclusively:

SCALA
val price = 100
// price = 120   // does not compile: reassignment to val

var counter = 0
counter += 1     // allowed, but avoid in core logic

Scala's default collections (List, Vector, Map, Set from scala.collection.immutable) are immutable too. "Changing" one gives you a new collection and leaves the original alone:

SCALA
val a = List(1, 2, 3)
val b = 0 :: a         // List(0, 1, 2, 3)
val c = a :+ 4         // List(1, 2, 3, 4)
println(a)             // List(1, 2, 3), unchanged

This is cheap because immutable collections share structure. 0 :: a does not copy a; it creates one new node pointing to the old list. If you need a mutable collection for performance, scala.collection.mutable has them, and good style is to keep them inside a single function and return an immutable result.

Why immutability helps:

  • Nothing can change a value behind your back, so you can pass it anywhere safely.
  • Values are automatically thread-safe to share, which is why concurrency gets easier.
  • Equality and hashing never change, so values are safe as map keys.
  • Debugging is simpler: a value has the same contents everywhere it appears.

What is a pure function?

A function is pure if:

  1. Its result depends only on its arguments, and
  2. It has no observable side effects: it does not modify outside state, print, read files, touch the network, throw exceptions for control flow or read the clock.
SCALA
// Pure: same input, same output, nothing else happens
def add(a: Int, b: Int): Int = a + b
def discount(price: Double, percent: Double): Double = price * (1 - percent / 100)

// Impure: depends on and changes hidden state
var total = 0
def addToTotal(n: Int): Int =
  total += n          // side effect: modifies outside state
  total               // the result depends on earlier calls

// Impure: depends on something other than its arguments
def greeting(name: String): String =
  s"Hello, $name! It is ${java.time.LocalTime.now()}"

Pure or impure?

Pure Result depends only on arguments. Nothing else happens.
Impure Reads or changes outside state, prints, or fails unpredictably.
1 / 2

Referential transparency

A pure function call can always be replaced by its result without changing the program. That property is called referential transparency:

SCALA
def square(n: Int): Int = n * n

val x = square(4) + square(4)
val y = 16 + 16          // exactly the same program

If square printed something or incremented a counter, the two lines would no longer be equivalent. Referential transparency is what lets you refactor fearlessly, memoize results and reorder independent computations.

Pushing effects to the edges

Real programs must read input, write to databases and print. The functional approach is not "no effects" but effects at the edges, pure logic in the middle:

SCALA
// Pure core: easy to test
def summarize(lines: List[String]): String =
  val words = lines.flatMap(_.split("\\s+")).filter(_.nonEmpty)
  s"${lines.size} lines, ${words.size} words"

// Thin impure shell
@main def run(): Unit =
  val lines = scala.io.Source.fromFile("notes.txt").getLines().toList
  println(summarize(lines))

summarize can be tested with a plain list in one line. Only run touches the file system.

Recursion instead of loops

Without var, how do you repeat things? Often with higher-order functions (the next lesson), and sometimes with recursion: a function that calls itself on a smaller problem.

SCALA
def sum(xs: List[Int]): Int = xs match
  case Nil => 0
  case head :: tail => head + sum(tail)

println(sum(List(1, 2, 3, 4)))   // 10

This reads like the definition: the sum of an empty list is 0; the sum of a list is its head plus the sum of its tail. Pattern matching (lesson) makes this style natural.

The problem: each call waits for the next, so the stack grows with the list. A list of a million elements can cause a StackOverflowError.

Tail recursion and @tailrec

A call is a tail call if it is the very last thing the function does. The compiler can turn a self-recursive tail call into a plain loop, using constant stack. The standard trick is an accumulator parameter that carries the partial result:

SCALA
import scala.annotation.tailrec

def sumTail(xs: List[Int]): Long =
  @tailrec
  def loop(rest: List[Int], acc: Long): Long = rest match
    case Nil => acc
    case head :: tail => loop(tail, acc + head)   // last action: the call itself
  loop(xs, 0L)

println(sumTail((1 to 1_000_000).toList))   // 500000500000

The accumulator is a Long because the total does not fit in an Int. A million elements pose no problem for the stack.

@tailrec does not cause the optimization; it makes the compiler fail if the function is not actually tail-recursive, protecting you from accidentally breaking it. Typical culprit: doing work after the recursive call (head + sum(tail) is not a tail call).

flowchart LR
    A["sum(List(1,2,3))"] --> B["1 + sum(List(2,3))"]
    B --> C["1 + (2 + sum(List(3)))"]
    C --> D["1 + (2 + (3 + 0))"]
    D --> E["6"]
    F["loop(List(1,2,3), 0)"] --> G["loop(List(2,3), 1)"]
    G --> H["loop(List(3), 3)"]
    H --> I["loop(Nil, 6) = 6"]

Top row: plain recursion keeps pending additions on the stack. Bottom row: tail recursion carries the result forward, so the same stack frame can be reused.

Same ideas in Kotlin and Java

Kotlin has tailrec and Java has no tail-call optimization at all, which is why Java programmers write loops. These runnable examples are Kotlin and Java, not Scala.

Kotlin Kotlin: tailrec accumulator (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Java Java: pure function versus hidden state (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Reaching for var first. Ask whether a map, fold or recursive function expresses the same thing.
  • Believing val makes an object immutable. val buf = ArrayBuffer(1) cannot be reassigned, but the buffer itself can still change.
  • Hidden effects: logging, println or reading System.currentTimeMillis inside a function that you consider pure.
  • Non-tail "tail" recursion, such as 1 + loop(...); @tailrec will tell you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which makes a function impure?

    A pure function's result must depend only on its arguments. Reading changing outside state breaks that.
  2. 2. What does val b = 0 :: a do to the immutable list a?

    Immutable lists are never modified. Prepending creates one new node that points at the existing list.
  3. 3. What does @tailrec do?

    The compiler optimizes self tail calls itself. The annotation only checks that the optimization is possible.
  4. 4. Why is head + sum(tail) not a tail call?

    In a tail call nothing remains to be done after the call returns. Here the result must still be added to head.

Summary

  • Prefer val and immutable collections; "changing" them creates new values with shared structure.
  • Pure functions depend only on arguments and have no side effects, so calls are referentially transparent.
  • Keep side effects at the edges of the program and the logic pure.
  • Recursion replaces loops; use an accumulator and @tailrec for stack-safe tail recursion.

Next: Higher-Order Functions and Currying