Scala Closure
In Scala, a function whose return value depends on one or more variables declared outside the function, is called as closure.In other term, we can say that function and variable declared outside are bound to each other.
Let’s understand this with an example. We have defined a function which performs a sum of 2 variables – first its arguments and second variable declared outside.
object closureExample { val b:Int = 2 def main(args: Array[String]): Unit = { println("Result of function sum(2) - "+sum(2)) println("Result of function sum(10) - "+sum(10)) } //Closure where function depends upon variable a declared outside def sum(a:Int):Int=a + b }
Output: Result of function sum(2) - 4 Result of function sum(10) - 12
Function return value will change if the value of variable that is declared outside , is changed. Let’s change the value of b as 5 and see the result.
object closureExample { val b:Int = 5 def main(args: Array[String]): Unit = { println("Result of function sum(2) - "+sum(2)) println("Result of function sum(10) - "+sum(10)) } //Closure where function depends upon variable a declared outside def sum(a:Int):Int=a + b }
Output: Result of function sum(2) - 7 Result of function sum(10) - 15
We can pass the function sum to other methods and functions as shown below. We have created another function printSum accepting same signature of function as its parameter along with an Int parameter.
object closureExample { val b:Int = 5 def main(args: Array[String]): Unit = { printSum(sum,20) printSum(sum,10) } //Closure where function depends upon variable a declared outside def sum(a:Int):Int=a + b def printSum(f:Int=>Int,x:Int)={ println(f(x)) } }
Output: 25 15