A closure can be defined as the function whose return value depends on the value of one or more variable defined outside this function. A closure is an instance of a function, a value whose non-local variables have been bound either to values or to storage locations.

Consider an example as below;

We are defining an object Divide with a main function that accepts arguments of String Array type and printing the value of the divider by calling a variable divider defined outside the main method where we divide the value passed to divider with the div value “2” initialized outside the main method.

i and div are the two free variables. i is the formal parameter to the function. div is not a formal parameter and has a reference to a variable outside the function but in the enclosing scope as

Run the above example by typing Divide.main(null)

Output:

Below image shows the above programs execution in Scala shell.

Free variables and bound variables

The variables that are used in function but are neither local variables nor formal parameters to the function are called free variables.

Consider an example for free variable;

Run by typing m1.main(null) and you will get output Total marks secured: 55.

Scala-free-bound-variables

A bound variable is a variable that was previously free, but has been bound to a specific value or set of values.

Consider an example for bound variable;

Run by typing result(32) and you will get output like res2: Int = 192.

Here i is bound to a new value each time the result is called.

Anonymous functions

An anonymous function is a function definition that is not bound to an identifier. In other words, the function definition doesn’t have an implicit name.

Consider an example for anonymous function as below;

As you can notice we have not specified any identifier for the function after the equal symbol. There is no binding associated with the function definition. This the reason why it is called as an Anonymous function. After the specification of the statement the interpreter gives an output as;

a has the object reference to this anonymous function and it can be called as a(4) that will produce output similar as res16: Int = 5. Below image shows execution of bound variable and anonymous function example in Scala shell.

Scala-anonymous-function

That’s all for Closures and anonymous functions in Scala programming, we will look into more Scala core features in coming posts.

By admin

Leave a Reply

%d bloggers like this: