closure

How to use closures in Scala (closure examples, syntax)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 9.5, “How to use closures in Scala (closure examples, syntax).”

Back to top

Problem

You want to pass a function around like a variable, and while doing so, you want that function to be able to refer to one or more fields that were in the same scope as the function when it was declared.

Back to top

Solution

You can demonstrate a closure in Scala with the following simple (but complete) example:

Table of Contents

  1. Problem
  2. Solution
Back to top