Scala - Closures Example

1. Introduction

Closures are a fundamental concept in functional programming and Scala embraces this concept fully. A closure is a function that maintains a reference to one or more variables outside of the function scope. They can capture and use variables that are defined in their enclosing scope. This blog post will introduce the concept of closures in Scala and provide examples to illustrate their usage.

Scala - Closures

In Scala, closures are functions that depend on one or more free variables. A free variable is a variable that is not defined within the function but is used in the function body. When the runtime encounters a closure, it "closes over" the free variable by capturing its current value. This means the function retains access to a variable even after the scope in which the variable was defined has ended.

2. Program Steps

1. Define a variable outside of the function scope.

2. Create a function that uses this variable, forming a closure.

3. Demonstrate how the closure maintains the state of the external variable.

4. Execute the program to observe the behavior of the closure.

3. Code Program

object ClosureDemo extends App {
  var number: Int = 10 // An external variable
  val addNumber: Int => Int = (x: Int) => x + number // A closure using the 'number' variable

  // Demonstrate closure behavior
  println(s"Calling closure with 5: ${addNumber(5)}")
  // Change the value of 'number' and call the closure again
  number = 20
  println(s"Calling closure with 5 after changing external variable: ${addNumber(5)}")


Calling closure with 5: 15
Calling closure with 5 after changing external variable: 25


1. We define a variable number outside of any function, which will be used by our closure.

2. addNumber is a function literal (lambda) that takes an integer x and adds the external variable number to it. Since it uses a variable not defined within its own scope, it forms a closure.

3. When addNumber is called with the value 5, it adds the current value of number (which is 10) to 5 and prints 15.

4. We then change number to 20 and call addNumber again with the same argument 5. The closure now uses the updated value of number, printing 25.

5. This shows that the closure has captured the number variable, and it's using the latest value of number at each call.