Saturday, 18 May 2019

Closures functions in Scala


Closures functions
Scala Closures are functions which uses one or more free variables and the return value of this function is dependent of these variable. The free variables are defined outside of the Closure Function and is not included as a parameter of this function. So the difference between a closure function and a normal function is the free variable. A free variable is any kind of variable which is not defined within the function and not passed as the parameter of the function. A free variable is not bound to a function with a valid value. The function does not contain any values for the free variable.
A closure function can further be classified into pure and impure functions, depending on the type of the free variable. If we give the free variable a type var then the variable tends to change the value any time throughout the entire code and thus may result in changing the value of the closure function. Thus this closure is a impure function. On the other-hand if we declare the free variable of the type val then the value of the variable remains constant and thus making the closure function a pure one.
Example:
object UVPM
{
    // Main method
    def main(args: Array[String])
    {
        println( "Final_Sum of first value = " + sum(1))
        println( "Final_Sum of second value = " + sum(2))
        println( "Final_Sum of third value = " + sum(3))
    }       
    var a = 44
    // define closure function
    val sum = (b:Int) => b + a
}
//Output:
Final_Sum of first value = 5
Final_Sum of second value = 6
Final_Sum of third value = 7
Here, In above program function sum is a closure function. var a = 4 is impure closure. the value of a is same and values of b is different.

No comments:

Post a Comment

Use filter method to filter a Scala collection

Use filter method to filter a Scala collection To use filter on your collection, give it a predicate to filter the collection elements as...