Home > front end >  Difference between calling a variable and creating a new value of the variable
Difference between calling a variable and creating a new value of the variable

Time:10-23

I am pretty sure this is something very simple that is going over my head, but if you can give me some clarity as to why in the following code snippet the third println(p()) returns 10 instead of 11. The final output is 5 8 10 7, I understand all of them except the moment it returns 10.

class A(var x : Int) {
  def f() : () => Int = {
    var y : Int = 1
    () => {y = y   2; y   x}
  }
}

object ClosureM2 {
  def main(args : Array[String]) : Unit = {
    var a = new A(2)
    var p = a.f()
    println(p())
    a.x = 3
    println(p())
    a = new A(4)
    println(p())
    p = a.f()
    println(p())
  }
}

CodePudding user response:

It looks like you're getting caught out where a is reassigned to A(4).

When we assign f() to the variable p, p is set to the function f() inside of the class A, not to the variable a:

var a = new A(2)
var p = a.f()

This means that when a is reassigned with a = new A(4), p doesn't point to the new A we have assigned to a. It is still pointing to the previous instance A.

Because of that, when p() is called again it calculates to 7 A(x = 3) which evaluates to 10.

  • Related