官术网_书友最值得收藏!

Closures

In our function definitions, we've referred to two different types of variables: the ones that are provided as parameters (bound variables) and others, which were defined in the enclosing block (free variables). The free variable is named so, because the function itself does not give any meaning to it.

A function that does not refer to any free variable is self-sufficient and the compiler can translate it to the bytecode in any context. Another way to state this is to say that this definition is closed in itself. It is named, accordingly, a closed term. A function referring to the free variables, on the other hand, can only be compiled in a context where all of these variables are defined. Therefore it is called open term and it closes over the free variables at the moment it is compiled, hence the name closure (over the free variables).

The usual scope resolution rules apply for closures in the same way that they apply for variables and other definitions as demonstrated by the next snippet:

scala> def outerA = {
| val free = 5
| def innerA = {
| val free = 20
| def closure(in: Int) = free + in
| closure(10)
| }
| innerA + free
| }
outerA: Int

scala> outerA
res3: Int = 35

The res3 is calculated as outerA.free (5) + innerA.free (20) + closure.in(10).

The free variable must be defined before the closure, otherwise, the compiler will complain:

scala> def noReference(in: Int) = {
| def closure(input: Int) = input + free + in
| }
def closure(input: Int) = input + free + in
^
On line 2: error: not found: value free

scala> def forwardReference(in: Int) = {
| def closure(input: Int) = input + free + in
| val free = 30
| }
def closure(input: Int) = input + free + in
^
On line 2: error: forward reference extends over definition of value free

The first try fails because we forgot to define a free variable. The second is still unsuccessful because the free variable is defined after the closure.

主站蜘蛛池模板: 蓬溪县| 曲靖市| 金湖县| 信丰县| 屯门区| 金沙县| 邯郸县| 惠州市| 岫岩| 嘉祥县| 缙云县| 祥云县| 汉沽区| 卓资县| 赣榆县| 宜州市| 格尔木市| 曲阳县| 赣州市| 灵璧县| 墨竹工卡县| 呼伦贝尔市| 长葛市| 宜章县| 若尔盖县| 成安县| 舞钢市| 长岛县| 弋阳县| 金坛市| 杭锦旗| 福海县| 东方市| 济南市| 宁波市| 天祝| 罗平县| 宜黄县| 峨山| 随州市| 本溪市|