8.26. Scala closure

发布时间 :2023-11-16 23:00:02 UTC      

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

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.