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

编程技术  /  houtizong 发布于 3年前   72

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.closureobject 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  }}

 

 

 

 

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客