Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

flutter - Is it possible to modify the reference of an argument in Dart?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, Dart does not pass arguments by reference. (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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...