0

I can conveniently change opsCount variable directly from inside the function, because there is only one of that type of variable.

int opsCount  = 0;      
int jobXCount = 0;       
int jobYCount = 0;
int jobZCount = 0;

void doStats(var jobCount) {
  opsCount++;      
  jobCount++;   
}   

main() {
  doStats(jobXCount);    
}

But there are many jobCount variables, so how can I change effectively that variable, which is used in parameter, when function is called?

1
  • If you can clarify what you mean by "that" variable, that might help. Commented Aug 27, 2014 at 21:52

2 Answers 2

1

I think I know what you are asking. Unfortunately, the answer is "you can't do this unless you are willing to wrap your integers". Numbers are immutable objects, you can't change their value. Even though Dart's numbers are objects, and they are passed by reference, their intrinsic value can't be changed.

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can wrap the variables, then you can pass them as reference:

class IntRef {
  IntRef(this.val);
  int val;
  @override
  String toString() => val.toString();
}

IntRef opsCount  = new IntRef(0);
IntRef jobXCount = new IntRef(0);
IntRef jobYCount = new IntRef(0);
IntRef jobZCount = new IntRef(0);

void doStats(var jobCount) {
  opsCount.val++;
  jobCount.val++;
}

main() {
  doStats(jobXCount);
  print('opsCount: $opsCount; jobXCount: $jobXCount; jobYCount: $jobYCount; jobZCount: $jobZCount');
}

EDIT

According to Roberts comment ..
With a custom operator this would look like:

class IntRef {
  IntRef(this.val);
  int val;
  @override
  String toString() => val.toString();

  operator +(int other) {
    val += other;
    return this;
  }
}

void doStats(var jobCount) {
  opsCount++;
  jobCount++;
}

1 Comment

You can just overload the operators for the IntRef class. So there is no need for var.val++;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.