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