Google News
logo
Scala - Interview Questions
What do you mean by Closure in Scala?
Scala closures are functions whose return value is dependent on one or more free variables declared outside the closure function. Neither of these free variables is defined in the function nor is it used as a parameter, nor is it bound to a function with valid values. Based on the values of the most recent free variables, the closing function is evaluated.

Syntax :
var x = 20   
def function_name(y:Int)    
{
println(x+y)
} ​

Example :
object FreeTimeLearn
{
    def main(args: Array[String])
    {
        println( "Sum(2) value = " + sum(2))
        println( "Sum(3) value = " + sum(3))
        println( "Sum(4) value = " + sum(4))
    }    
    var x = 20
    val sum = (y:Int) => y + x
}​
 
Output :
Sum(2) value = 22
Sum(3) value = 23
Sum(4) value = 24​

In the above program, the sum is a closure function. var x = 20 is an impure closure. As can be seen, x is the same, and y is different.
Advertisement