← Back to Scala Course | Chapter 9: Functional Programming | Lesson 4 of 8

Closures

In this page:

  1. Closures

Closures

A closure is a function that captures variables from its enclosing scope, continuing to reference them even after that scope has technically finished executing. This lets you build functions that carry their own private, remembered state. Closures are what make patterns like counters or configurable multiplier functions possible without a class.

Note: A closure captures the variable itself, not just its value at creation time -- if the captured var changes later, the closure sees the new value.

Example: Closures

markup
object Main extends App {
  def makeMultiplier(factor: Int): Int => Int = {
    (x: Int) => x * factor
  }

  val triple = makeMultiplier(3)
  val double = makeMultiplier(2)

  println(triple(5))
  println(double(5))
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.