Scala:如何使闭包不看其自由变量的变化?

时间:2017-08-20 14:10:06

标签: scala

在以下代码段中,关闭foo会在scala中看到x中所做的更改。但是,如何让y中的局部变量foo永久保留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

2 个答案:

答案 0 :(得分:1)

你可以这样做:

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

在这种情况下,x绑定在foo中。

您正在做的是closure的一个例子。

答案 1 :(得分:1)

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