munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.75k stars 1.03k forks source link

Can't understand how Set expression works in jlox #979

Closed Ach113 closed 3 years ago

Ach113 commented 3 years ago

Taken from the chapter 12 (Classes), this is how visitor of Set expression is defined:

 @Override
  public Object visitSetExpr(Expr.Set expr) {
    Object object = evaluate(expr.object); // object is declared here

    if (!(object instanceof LoxInstance)) { 
      throw new RuntimeError(expr.name,
                             "Only instances have fields.");
    }

    Object value = evaluate(expr.value);
    ((LoxInstance)object).set(expr.name, value); // set is called on object, its field "fields" gets updated with new value
    return value; // object goes out of scope
  }

I don't understand how this affects the state of the callee object. Here we see that object field of Set gets evaluated to get the callee, then .set() method gets called, which changes the state of Object object, but when function returns, doesn't the change caused by the .set() method get discarded?

nocturn9x commented 3 years ago

The method changes the data in-place, so no, it does not get discarded

munificent commented 3 years ago

but when function returns, doesn't the change caused by the .set() method get discarded?

No. In Java, all objects are passed by reference. The object goes out of scope in this function, but the original object retains its modifications.