WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Scala · Basic · question 12 of 100

Explain the concept of closures in Scala with an example.?

📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

In Scala, a closure is a function that captures and retains references to the free variables from its surrounding or enclosing scope. Free variables are those variables that are not declared within the function itself and are used by the function. This ability to "close over" free variables allows closures to maintain the state between multiple invocations, even if the variables are not instantiated within the closure.

A simple example of a closure in Scala can be a function that generates another function. Consider the following code:

def addGenerator(x: Int): Int => Int = {
  // This is a closure because it captures the 'x' variable from its surrounding scope.
  def adder(y: Int): Int = x + y
  adder
}

Here, the ‘addGenerator‘ function takes an integer ‘x‘ as a parameter and returns a function ‘adder‘ that takes another integer ‘y‘ and returns their sum. The ‘adder‘ function, in turn, is a closure since it captures the ‘x‘ variable from the surrounding scope of the ‘addGenerator‘ function. In other words, the state of ‘x‘ is preserved within the ‘adder‘ function, even if it is not instantiated within the ‘adder‘ function itself.

Let’s see how it works when invoked:

val addFive = addGenerator(5)
val sum1 = addFive(10) // sum1 = 15
val sum2 = addFive(20) // sum2 = 25

In this example, we first create a new function ‘addFive‘ by invoking the ‘addGenerator‘ with the argument ‘5‘. The resulting ‘addFive‘ function has already captured the value ‘x = 5‘ in its closure, so it always adds 5 to the input parameter ‘y‘.

Invoking ‘addFive(10)‘ will yield ‘15‘, and invoking ‘addFive(20)‘ will yield ‘25‘. As you can see, the state of ‘x‘ is preserved even when the closure is invoked multiple times, and the environment of ‘addGenerator‘ is "closed over" by the ‘adder‘ function, hence the term "closure".

Closures can become particularly useful in functional programming when you want to create customized functions or maintain a state without using mutable data structures or side-effects. Keep in mind that capturing mutable data structures in closures can lead to subtle bugs or unintended side-effects as multiple invocations of the closure might change its state across calls. In such cases, it’s often better to rely on immutable data structures and pure functions.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview — then scores it.
📞 Practice Scala — free 15 min
📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

All 100 Scala questions · All topics