Is it possible to modify the reference of an argument in Dart?
Asked Answered
F

2

7

Not sure if the terminology in the title is 100% correct, but what I mean is easily illustrated by this example:

class MyClass{
  String str = '';  
  MyClass(this.str);
}


void main() {
  MyClass obj1 = MyClass('obj1 initial');

  print(obj1.str);

  doSomething(obj1);  
  print(obj1.str);

  doSomethingElse(obj1);
  print(obj1.str);
}



void doSomething(MyClass obj){
  obj.str = 'obj1 new string';
}

void doSomethingElse(MyClass obj){
  obj = MyClass('obj1 new object');
}

This will print

obj1 initial
obj1 new string
obj1 new string

But what if I wanted doSomethingElse() to actually modify what obj1 is referencing, so that the output would be:

obj1 initial
obj1 new string
obj1 new object

Is this possible in Dart, and if so, how?

Fibrinolysin answered 21/3, 2019 at 9:4 Comment(0)
S
9

No, Dart does not pass arguments by reference (Dart is pass-by-assignment/call-by-sharing). (Without something like C++'s complex type system and rules, it's not clear how it would work if the caller didn't bind the argument to a variable.)

You instead could add a level of indirection (i.e., by putting obj1 inside another object, such as a List, Map, or your own class). Another possibility would be to make doSomethingElse a nested function, and then it could directly access and modify variables in the enclosing scope.

Schear answered 22/3, 2019 at 2:34 Comment(0)
P
4

You have a reference problem in that function,

When you call doSomethingElse(obj1) in main your,

MyObject obj parameter referencing the obj1 value,

then obj you're referencing the MyClass('obj1 new objcet'),

and you're not changing the obj1 reference in the main

void doSomethingElse(MyClass obj){ // let's say we gave the parameter obj1
  // here obj referencing the obj1 value
  obj = MyClass('obj1 new object');
  //and then it is referencing the MyClass('obj1 new object') value
  //nothing change for obj1 it still referencing the same value
}

You can return that object and give reference to that object like this,

class MyClass {
  String str = '';
  MyClass(this.str);
}

void main() {
  MyClass obj1 = MyClass('obj1 initial');

  print(obj1.str);

  doSomething(obj1);
  print(obj1.str);

  obj1 = doSomethingElse();
  print(obj1.str);
}

void doSomething(MyClass obj) {
  obj.str = 'obj1 new string';
}

MyClass doSomethingElse() {
  return MyClass('obj1 new object');
}

output : enter image description here

Ply answered 21/3, 2019 at 11:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.