【Scala十四】Scala核心八:闭包

Free variable A free variable of an expression is a variable that’s used inside the expression but not defined inside the expression. For instance, in the function literal expression (x: Int) => (x, y), both variables x
and y are used, but only y is a free variable, because it is not defined inside the expression.


Bound variable A bound variable of an expression is a variable that’s both used and defined inside the expression. For instance, in the function literal expression (x: Int) => (x, y), both variables x and y are used,
but only x is bound, because it is defined in the expression as an Int and the sole argument to the function described by the expression.

 

 

closure A function object that captures free variables, and is said to be “closed” over the variables visible at the time it is created.

闭包是一个函数对象,当闭包中的自由变量绑定了具体的值后,称之为闭包

 

 

问题:

对于闭包(x: Int) => (x, y),当闭包建立后,y的值发生改变,调用闭包时,y的值是建立时的值还是改变的值?答案是改变后的值。也就是说,闭包函数是在调用执行时才从当前的上下文中获取到y的值

 

 

 

package spark.examples.scala.closure

object ClosureTest {

  def sum(args: List[Int]) = {
    var sum = 0
    //sum += _是函数常量,其中sum是自由变量
    val calc = sum += (_: Int)
    args.foreach(calc)
    println("sum1: " + sum) //6, sum是自由变量,计算结束后,sum的值在闭包内的变化,能够在外面也看到
    args.foreach(calc) //sum的值改变后,函数常量能够看到这个变化,再次计算结果12
    println("sum2: " + sum) //12,
  }

  def increaseBy(offset: Int) = {

    def add(x: Int) = {
      x + offset
    }
    add _
    //方法体可以直接使用 (x: Int) => x + offset
  }

  def main(args: Array[String]) {
    val args = List(1, 2, 3)
    sum(args)
    println(increaseBy(10)(100)) //110
  }
}

 

 

 

 

你可能感兴趣的:(scala)