I want to know does my code represent a closure concept
?
object Closure {
val fun = (x: Int) => x + 1
def clj = (y: Int) => y * fun(y)
}
Here is my runner code.
object App {
def main(args: Array[String]) {
val c = Closure
val result = c.clj(10)
println(result)
}
}
Suppose, the closure code is
def clj = (y: Int) => y * fun(y)
Or maybe I'm wrong?
It isn't, because it doesn't close over anything.
This would be a closure:
object Foo {
def clj(a: Int) = { (b: Int) => a + b }
}
This is:
object
called Foo
... clj()
... The returned inner function captures (or closes over ) the value of a
at the time clj()
is called, conceptually keeping it alive.
Thus:
val f1 = Foo.clj(10) // returns a function that adds 10 to whatever is passed
f1(100) // => 110
The Wikipedia entry on closures actually contains a decent description of the concept.
https://en.wikipedia.org/wiki/Closure_(computer_programming)
在我看到闭包概念时,是的,您在clj
的代码表示闭包,因为它引用了外部函数fun
,即闭包术语中的所谓“环境”。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.