Jonathan
Jonathan

Reputation: 4928

Calling a function with two same arguments, but setting the second while calling

I am calling a function that expects two arguments. I use the same variable, but at the second argument I set this variable to another thing. See below:

https://dartpad.dartlang.org/2156442de07f56d90b430bc67f3461ac

void main() {
  String s = 'oi';

  aa(s, s = 'oi2');
}
void aa(String buf, String buf2){
  print('$buf, $buf2');
}

This will print "oi, oi2". I want this to happen. I am using a modified notification within properties, like:

set title(String n) {
    this.modified('title', _title, _title = n);
}

However, I wonder if this can be seen as a bug or it is expected.

thanks, Joe

Upvotes: 4

Views: 72

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658263

s is a String which are passed by value, not by reference.

aa(s, s = 'oi2');

evaluates the first parameter s, which is 'oi'
next s = 'oi2' is evaluated, which means s gets 'oi2' assigned
then the result of s = 'oi2' (which is 'oi2') is passed as 2nd parameter.

After aa(s, s = 'oi2'); s has the value oi2.

See also https://gist.github.com/floitschG/b278ada0316dca96e78c1498d15a2bb9

Upvotes: 2

lrn
lrn

Reputation: 71903

Evaluation order of arguments is left-to-right, so you can rely on the first argument's value being found by evaluation s to "ii", and then second argument's value is the value of the assignment s = 'oi2 - which evaluates to "oi2" (and not, technically, by reading the variable, it just happens that the variable is written to with the same value before the function is called).

It is expected - if any implementation does something else, it's broken.

Upvotes: 1

Related Questions