Ra Ka
Ra Ka

Reputation: 3055

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. However, how can I make local variable y in foo hold value of x permanently and not see changes?

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

Upvotes: 0

Views: 136

Answers (2)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22605

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.

What you are doing is an example of closure.

Upvotes: 2

dkim
dkim

Reputation: 3970

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

Upvotes: 1

Related Questions