简体   繁体   English

Scala:如何使闭包不更改其自由变量?

[英]Scala: How to make a closure not to see changes in its free variable?

In the following code snippet, closure foo see the changes made in x as it should in scala. 在以下代码段中,闭包foo看到x在scala中所做的更改。 However, how can I make local variable y in foo hold value of x permanently and not see changes? 但是,如何使foo局部变量y永久持有x的值,而看不到更改?

scala> var x = 10
x: Int = 10

scala> val foo = (a:Int) => {val y = x; a + y}
foo: Int => Int = <function1>

scala> foo(3)
res1: Int = 13

scala> x = 5
x: Int = 5

scala> foo(3)    //see changes made in x. But how can I make closure not to see changes made on x?
res2: Int = 8

You could do something like this: 您可以执行以下操作:

val foo = ((x:Int) => (a:Int) => {val y = x; a + y})(x)

In this case, x is bound in foo. 在这种情况下,x绑定在foo中。

What you are doing is an example of closure . 您正在做的事情就是关闭示例。

scala> var x = 10 x: Int = 10 scala> val foo = { val y = x; (a: Int) => a + y } foo: Int => Int = $$Lambda$1027/1344946518@5416f8db scala> foo(3) res0: Int = 13 scala> x = 5 x: Int = 5 scala> foo(3) res1: Int = 13

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM