What is a Closure in Scala ? Why it is required ? How to use it ?

Analyzing data.
Reading Time: 2 minutes

Objects are more flexible for certain use cases because they carry both data members and member functions, whereas a function does not have data members.

So if there is a requirement to pass data members along with functions, How will we achieve it in functional programming ?

The answer is yes, we can achieve it using a closure and a free variable.

What is a Closure ?

A closure is a function that uses one or more “free variable”, it may be pure or impure depending on the which type of free variable we are using in a closure function.

It can be either a named or anonymous function. The return value of the closure depends on the free variable defined outside this function.


Free variable

A free variable is a normal variable and can be pure or impure depending on the use case.

Eg of an impure free variable

var status = "Available"
status = "Out of Stock"

The closure will take the most recent value of the free variable if its value is changing continuously.


Let’s try to understand the closure and free variable using a working example:

source code
Source code


Let’s observe how this code is working:
1. So productStatus is a function that takes a function and a string as an argument.
2. then it passes that string argument “productName” in the function f.
3. Now let’s come to function “f” which is defined inside the object ClosureExample.
4. f/displayProductStatus is a closure function that takes productName as an argument and uses a free variable “status” that denotes the status of that product and prints the result.
5. status is a free variable whose value is changing on the basis of product availability.


So this is how we used the closure function displayProductStatus and free variable status to support the end function productStatus.


For more context use this link.
Scala official documentation.
My previous articles.

Written by 

Pallav is working as Software Consultant at Knoldus Inc. He is a technology enthusiast and a keen learner with more than 2 years of experience. He works as a Quality Catalyst in the organization. He has a good understanding of programming languages like Java and Scala. He likes to listen to songs and playing table tennis.