8.26. Scala closure

发布时间 : 2025-10-25 13:35:10 UTC      

Page Views: 14 views

A closure is a function and the return value depends on one or more variables declared outside the function.

Generally speaking, a closure can be simply thought of as another function that can access local variables in a function.

Such as the anonymous function below:

val multiplier = (i:Int) => i * 10 

There is a variable I in the body of the function, which is used as an argument to the function. Like another piece of code below:

val multiplier = (i:Int) => i * factor 

In multiplier there are two variables in: I and factor . One of the I is the formal argument of the function, in the multiplier When the function is called, I is assigned a new value. However, factor is not formal parameters, but free variables, consider the following code:

var factor = 3 val multiplier = (i:Int) => i * factor 

Here we introduce a free variable. factor , this variable is defined outside the function.

Function variables defined in this way multiplier it becomes a “closure” because it refers to the variable defined outside the function, and the process of defining this function is to capture the free variable toform a closed function.

Complete instance

Example

object Test { def main(args: Array[String]) { println( "muliplier(1) value = " + multiplier(1) ) println( "muliplier(2) value = " + multiplier(2) ) } var factor = 3 val multiplier = (i:Int) => i * factor } 

Execute the above code, and the output is as follows:

$ scalac Test.scala $ scala Test muliplier(1) value = 3 muliplier(2) value = 6 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。