September 30, 2025

Scala – Closure

A closure in Scala is a function and the concept of closure is quite clear. However I have decided to discuss closure under its own lesson since it is a concept unique to Scala programming language.

So a closure is a function that uses a variable declare outside the function. Let’s take an example of the function below.

def makeUp(score: Double) = score + bonus

In the example, we see a function called makeUp that takes a parameter, score. However, you also see that this function uses another variable called bonus. So where is the bonus coming from? It is a free variable. What??

 

Free Variable

So what is heck is a “free variable”?  It is not a parameter to the makeUp() function. Besides, it’s not also a local variable to the function. It is defined elsewhere outside the function such that the makeUp() function is free to use it. So we say the variable bonus is free variable to the makeUp() function.

Of course, if you try to compile the code above, it throws an error.  So you must have the variable defined as shown below for the code to compile.

// Program to demostrate Closure
object HigherOrderFunctions {

  val bonus: Int = 20
  def makeUp(score: Double) = score + bonus

  def main(args: Array[String]): Unit ={
    val finalScore: Double = makeUp(67.5);
    println("Final Score: " + finalScore)
  }

}

This works as expected and produces the following output

Final Score: 87.5

 

Topics on Functions in Scala

  1. Function Declaration and Definition
  2. Calling a Function
  3. Nested Functions
  4. Function Call by Name
  5. Functions With Variable Parameters
  6. Functions With Default Arguments
  7. Functions With Named Arguments
  8. Recursive Functions
  9. Anonymous Functions
  10. Partially Applied Functions
  11. Higher-Order Functions (HOD)
  12. Currying Functions

Leave a Reply