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

Closures

A closure is a function that remembers the variables around it when it was made, like a lunchbox that still holds what you packed. Even later, it can still use those values.

In this page:

  1. Closures
Syntax
scala
var captured = value
val closure = (param: Type) => param + captured    // uses captured from the outer scope

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))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a closure to copy the value of factor, when it captures the variable, so a var that changes later affects it.
  2. Creating closures in a loop over a var and being surprised that they share the same variable.
  3. Forgetting the return type Int => Int on makeMultiplier, so the compiler cannot infer the result clearly.
🔒

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.