Dart passes-by-value where the value is a reference to the object
As jamesdlin said:
I would consider Dart to be like many object-oriented languages in that it is always pass-by-value and that the value of an object is a reference to it. In a true pass-by-reference system, a callee can modify variables in the caller (as with C++'s reference parameters).
What does that mean?
Say I write my home address on a piece of paper and give it to you. If you go away and tear up the paper or cross out the address and write a different one, that doesn't change my home or my address. I still have the same home and the same address no matter what you do to the piece of paper I gave you.
However, if you use the address that I wrote on the paper to find my home, you could paint the building or take away the trash or plant a flower. That would change some things about my home, but it wouldn't change the address.
It's the same thing with Dart. You can pass a variable off as an argument to some function. If the object that the variable refers to is mutable, the function can change the state of the object, but it can't change where that object is stored in memory.
Example
Here is the Dart version of the story above, inspired from this Java example.
void main() {
Home addressToMyHome = Home('blue');
Home myAddressCopy = addressToMyHome;
print('My home is ${addressToMyHome.color}.');
print('Here is my address.');
writeNewAddressOnPaper(addressToMyHome);
print('But my home is still ${addressToMyHome.color}.');
print('Here is my address again.');
goToMyHomeAndPaintIt(addressToMyHome);
print('Now my home is ${addressToMyHome.color}.');
if (addressToMyHome == myAddressCopy) {
print('My address has not changed, though.');
}
}
void writeNewAddressOnPaper(Home home) {
home = Home('purple');
print('You made a new ${home.color} home.');
}
void goToMyHomeAndPaintIt(Home home) {
home.color = 'purple';
print('You are painting my home ${home.color}.');
}
class Home {
String color;
Home(this.color);
}
This prints the following story:
My home is blue.
Here is my address.
You made a new purple home.
But my home is still blue.
Here is my address again.
You are painting my home purple.
Now my home is purple.
My address has not changed, though.
Note that the variable addressToMyHome
does not contain the Home
object itself, but only a value of where the Home
object is stored in memory.