Is there a way to pass a primitive parameter by reference in Dart?

后端 未结 4 567
既然无缘
既然无缘 2020-12-01 17:51

I would like to pass a primitive (int, bool, ...) by reference. I found a discussion about it (paragraph \"Passing value types by reference\") here: value types in Dart, bu

4条回答
  •  被撕碎了的回忆
    2020-12-01 18:32

    They are passed by reference. It just doesn't matter because the "primitive" types don't have methods to change their internal value.

    Correct me if I'm wrong, but maybe you are misunderstanding what "passing by reference" means? I'm assuming you want to do something like param1 = 10 and want this value to still be 10 when you return from your method. But references aren't pointers. When you assign the parameter a new value (with = operator), this change won't be reflected in the calling method. This is still true with non-primitive types (classes).

    Example:

    class Test {
      int val;
      Test(this.val);
    }
    
    void main() {
      Test t = new Test(1);
      fn1(t);
      print(t.val); // 2
      fn2(t);
      print(t.val); // still 2, because "t" has been assigned a new instance in fn2()
    }
    
    void fn1(Test t) {
      print(t.val); // 1
      t.val = 2;
    }
    
    void fn2(Test t) {
      t = new Test(10);
      print(t.val); // 10
    }
    

    EDIT I tried to make my answer more clear, based on the comments, but somehow I can't seem to phrase it right without causing more confusion. Basically, when someone coming from Java says "parameters are passed by reference", they mean what a C/C++ developer would mean by saying "parameters are passed as pointers".

提交回复
热议问题