- Learn Scala Programming
- Slava Schmidt
- 354字
- 2021-06-10 19:35:48
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.
- Cocos2d Cross-Platform Game Development Cookbook(Second Edition)
- Learning LibGDX Game Development(Second Edition)
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- R語言數據分析從入門到精通
- Linux C/C++服務器開發實踐
- JavaScript+jQuery開發實戰
- Spring Boot+Spring Cloud+Vue+Element項目實戰:手把手教你開發權限管理系統
- Tableau Desktop可視化高級應用
- 從零學Java設計模式
- SAP Web Dynpro for ABAP開發技術詳解:基礎應用
- SQL Server 2008實用教程(第3版)
- Java編程指南:語法基礎、面向對象、函數式編程與項目實戰
- MySQL核心技術與最佳實踐
- jQuery Essentials
- Practical Linux Security Cookbook