Saturday 14 November 2015

Method, Function and Closure in Scala

var factor = 2
val multiplier = (i: Int) => i * factor

Because functions are first-class in Scala, we can define values that are functions.
factor is not a formal parameter, but a free variable, a reference to a variable in the enclosing scope.

Function:
An operation that is named or anonymous. Its code is not evaluated until the function is called. It may or may not have free variables in its definition.

A function in Scala is an object or, moreover, an object implementing one of the function traits.
A one parameter function implements Function1, a two parameter function implements Function 2 and so on.
When we create a variable whose value is a function object and when we call this function, the call gets converted into a call to the apply method. When we create a variable whose value is a function object and when we call this function, the call gets converted into a call to the apply method.

Closure:
A function closes over its environment to bind variables in scope to free variables within the function.

def multiplier(i: Int) = i * factor

A Scala method is a part of a class. A method has a name and a signature.

scala> def mult(n: Int) = n * 2
mult: (n: Int)Int
scala> val mult_fun = mult _
mult_fun: Int => Int = <function1>

This is the Eta expansion that is used to lift a method
When a method is used where a function is required. we say that Scala lifts the method to be a function.

No comments:

Post a Comment