liveBook · Manning

Closure

As explained in Elixir in Action, Third Edition

A closure is a function value that retains access to variables from the lexical scope where it was created.

A closure is a function value that retains access to variables from the lexical scope where it was created. Holding the function reference also keeps those captured variables reachable. In Elixir, closures appear naturally in lambdas passed to collection functions and concurrent processes. section 2.4.9 section 5.2.1

Capturing a value for concurrent work

Define a function that accepts a query description, then spawn an inner function that uses it: `async_query = fn query_def -> spawn(fn -> query_result = run_query.(query_def); IO.puts(query_result) end) end`. Calling `async_query.("query 1")` passes the query data into the new process through the closure. Running it over `1..5` starts five independent computations; results can appear in any order. section 5.2.1 section 5.2.1

Closures have two practical properties:

  • They capture a specific memory location, so rebinding a variable later does not change what an existing closure observes. section 2.4.9
  • They can shorten callbacks: `Enum.each([1, 2, 3], &IO.puts/1)` replaces an explicit lambda while preserving the function argument. section 2.4.9
  • They do not provide shared mutable state between BEAM processes; captured data is deep copied when passed to another process. section 5.2.1

How Elixir in Action, Third Edition covers it

How deep it goes
Explains lexical capture, rebinding, reachability, process copying, and callback syntax, but stops short of broader closure implementation internals.
Examples
Demonstrates callback printing, compact captured lambdas, rebinding behavior, and five concurrent queries.
What it assumes
Assumes basic Elixir lambdas and function calls while demonstrating lexical capture and process isolation through runnable examples.
What you can do after
Apply closures to write compact callbacks and pass immutable data into spawned concurrent computations.
How it connects
Connects closures with lambda functions, lexical scope, higher-order functions, capture operators, processes, and message passing.

Also explained in

Compare how 20 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.