Closures

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.

object test {
   var factor = 4
   val multiplier = (i:Int) => i * factor
 
  def main(args: Array[String]) {
      println( "multiplier(1) value = " +  multiplier(1) )
      println( "multiplier(2) value = " +  multiplier(2) )
}
}


Closure:-A closure is a function, whose return value depends on the value of one or more variables declared outside this function.

The following piece of code with anonymous function.
val sum=(a:Int,b:Float)=>a+b
sum(2,3)

var c=7
val sum1=(a:Int,b:Int)=>(a+b)*c

sum1(2,3)

outPu1t 35

Lests change the value of c=9
sum1(2,3)
outPut-45

In our example, ‘a’ and ‘b’ are formal parameters to the function sum1. ‘c’, however, is a reference to a variable in the enclosing scope. Scala closes over ‘c’ here.

var age=22
val sayhello=(name:String)=>println(s"I am $name and I am $age")
sayhello("Ayushi")


def func(f:String=>Unit,s:String){
      f(s)
     }
func(sayhello,"Ayushi")

No comments:

Post a Comment