Programming Notes(Scala Closure)

Some understanding of closure in Scala.

Closure, or functional closure to distinguish itself from closure in abstract algebra, refers to a function that refers to an outer variable. This passage explains its meaning in practice and tested the support for closure in Scala.
First we need some basic knowledge about functional programming. Functional programming is a programming paradigm, its main featrue is “functions first”, which means it treats functions as the most important element. Functions can be passed as a parameter, or returned as a return value.
This means declaration as follows is possible:

def fun(a: Int): (Int => Int) = {
b => a + b

The above function has a return value which is actually a function. This function’s type is(Int => Int), which indicates it takes an Integer as input, and returns an Integer. Then altogether this function is the return value of fun(a: Int).
So what does this have to do with closure? Let’s look at the inner function, which is actually an anonymous function:

b => a + b

It takes b as input, and return the sum of a and b. Here we should pay attention to a, because it is, as we’ve said before, an “outer variable”. We can see that a is passed in the inner function by the outer function fun(a: Int). So if not in this context, a in the inner function is unassigned, which means it’s not legal. But in this context, with the support of Scala language, closures like this can be supported. Let’s first call fun(a) once(In the scala REPL):

scala> fun(1)
res0: Int => Int = <function1>

So, here we have res0 as the return function. Normally the a that was passed into fun(a) is irrelevant now, if the return value is not a function. But here as it is a function that referenced a’s value, Scala has to help us record it:

scala> res0(2)
res1: Int = 3

So Scala has helped the inner function to record a’s value when it was constructed, and this proved that Scala supports closure, in fact all of the functional programming languages support this feature.