Scala closure


Release date:2023-11-17 Update date:2023-11-17 Editor:admin View counts:134

Label:

Scala closure

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

Powered by TorCMS (https://github.com/bukun/TorCMS).