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?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
heiklap
  • 85
  • 1
  • 2
  • 7

2 Answers2

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?

Community
  • 1
  • 1
Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
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++;
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    You can just overload the operators for the IntRef class. So there is no need for var.val++; – Robert Aug 28 '14 at 07:56