Scala:它是一个闭包吗?

Scala: Is it a closure?

我想知道我的代码是否代表 closure concept

object Closure {
  val fun = (x: Int) => x + 1
  def clj = (y: Int) => y * fun(y)
}

这是我的跑步者代码。

object App {
  def main(args: Array[String]) {
    val c = Closure
    val result = c.clj(10)
    println(result)
  }
}

假设,关闭代码是

def clj = (y: Int) => y * fun(y)

或许我错了?

正如我所看到的闭包概念,是的,您在 clj 中的代码代表一个闭包,因为它引用了一个外部函数 fun,闭包术语中所谓的 "environment"。

不是,因为它不会关闭任何东西。

这将是一个闭包:

object Foo {
  def clj(a: Int) = { (b: Int) => a + b }
}

这是:

  • 一个 objectFoo ...
  • 包含函数 clj() ...
  • 那个returns另一个函数。

返回的内部函数在 clj() 被调用时捕获(或 关闭 a 的值,在概念上保持其活动。

因此:

val f1 = Foo.clj(10) // returns a function that adds 10 to whatever is passed
f1(100)              // => 110

关于闭包的维基百科条目实际上包含了对该概念的恰当描述。

https://en.wikipedia.org/wiki/Closure_(computer_programming)