What is a Closure in Scala?

Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-27 00:36:44 Viewed : 294


In Scala, a closure is a function that captures and retains references to variables from its containing lexical scope, even after that scope has exited. Closures are an important concept in functional programming and allow you to create functions that "close over" their environment, meaning they can access and manipulate variables from the surrounding context, even if those variables are no longer in scope.

Here is an example to illustrate closures in Scala:

scala
object ClosureExample { def main(args: Array[String]): Unit = { val x = 10 // Closure: This function "closes over" the variable x val addX = (y: Int) => y + x // Call the closure val result = addX(5) println(s"Result of addX(5): $result") } }

In this example:

  • We define a variable x with a value of 10 in the main method.

  • We create a closure addX, which is a function that takes an argument y and adds it to the variable x. Even though x is not a parameter of addX, the closure can access x because it "closes over" it. This means that x is captured and retained by the closure.

  • We call the closure addX with an argument of 5. Inside the closure, it accesses the variable x, which is no longer in scope in the main method. However, due to the closure capturing x, it can still access and use its value.

When you run this code, it will print:

scss
Result of addX(5): 15

The closure addX has access to the variable x from its enclosing scope, and it can use that variable even after the main method has completed.

Closures are a powerful feature in functional programming as they enable the creation of functions with behavior that depends on their surrounding context. They are commonly used for creating higher-order functions, like mapping and filtering functions, as well as for creating callbacks and anonymous functions in Scala.

Search
Related Articles

Leave a Comment: