Friday, 29 August 2014

Scala Note 23: Closures


(x: Int) => x + more

This function has 'more' in its argument, 'more' is a free variable. By contrast, 'x' is a bound variable, which is defined as the function's parameter, an Int.

The function value created at runtime from this function literal is call a closure, which means "closing" the function literal by capturing the bindings of its free variables.
By contrast, a function literal with no free variables, is called a closed term.

What happens if 'more' changes after the closure is created?
The answer is the closure sees the change.
For example,

var more = 1
val addMore = (x: Int) => x + more
addMore(10) //11
more = 9999
addMore(10)//10009

Scala's closure capture variables themselves, not the value to which variables refer.
The instance used is the one that was active at the time the closure was created.
Each time the function is called, it will create a new closure.

The captured parameter lives out on the heap, instead of the stack, and thus can outlive the method call that created it.


No comments:

Post a Comment