Scala学习笔记16【Scala闭包代码实例】

package com.yl.scala

object Test {
  def main(args : Array[String]){

    val data = List(1,2,3,4,5)
    var sum = 0
    data.foreach(sum += _)
    println("sum:" + sum)

    def addFunction(more: Int) = (x : Int) => more + x  //more是个自由变量,x变量是一个绑定变量

    //只有赋予more一个准确的值,函数才能正常工作
    val a = addFunction(5) //相当于 def a(x: Int) = 5 + x
    val b = addFunction(55)

    a(103)  //相当于a(103) = 5 + 103
    b(124) // 相当于b(124) = 55 + 124
    println("a(103) = " + a(103))
    println("b(124) = " + b(124))


    def f(more: Int) = (x : Int) => more / x
    val aa = f(5555) //相当于 def aa(x: Int) = 5555 / x
    val bb = f(555)  //相当于 def bb(x: Int) = 555 / x
    println("aa(55) = " + aa(55))
    println("bb(5) = " + bb(5))

  }
}

运行结果:

sum:15
a(103) = 108 b(124) = 179 aa(55) = 101 bb(5) = 111

你可能感兴趣的:(scala,闭包)