Free preview.You're sampling one lesson — enroll free to unlock all 8 lessons and track your progress.
Enroll free
lesson

Pure Functions

Pure Functions

In this lesson — part of Functional Foundations — you'll learn pure functions in Scala and why it matters in real work.

Why it matters

Functional style — pure functions and immutability — makes code easier to test and reason about.

Key ideas

  • Pure functions
  • Immutability
  • No shared mutable state
  • Predictable outputs

In practice

Here's how it looks in idiomatic Scala:

// pure, immutable, expression-oriented
def factorial(n: Int): Int =
  if n <= 1 then 1 else n * factorial(n - 1)

val nums = List(1, 2, 3, 4)
val result = nums
  .filter(_ % 2 == 0)
  .map(_ * 10)
  .foldLeft(0)(_ + _)   // 60, no mutable accumulator

val composed = ((_: Int) + 1).andThen(_ * 2)(3) // 8

Scala note: Scala is not purely functional, but its immutable-by-default collections and expression-oriented syntax make foldLeft/map pipelines idiomatic — and @tailrec can guarantee a self-recursion is optimized into a loop.

Try it yourself

Exercise: In Scala, rewrite a function that mutates a global so it's pure.

Recap

You now understand pure functions and can apply it in Scala. Mark this lesson complete and continue to the next one.