Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an efficient operator+=

Tags:

dart

It looks as if operator+= is not something that can be user defined (from Dart Language Specification):

The following names are allowed for user-defined operators: <, >, <=, >=, ==, -, +, /, ̃/, *, %, |, ˆ, &, <<, >>, []=, [], ̃.

However, if you provide an operator+(...) then that is used when operator+= is called.

The question I have is, how do you effect an efficient operator+=() without requiring the creation of a new instance?

class DividendBreakdown {

  DividendBreakdown(this.qualified, this.unqualified, this.capitalGainDistribution);

  bool operator==(DividendBreakdown other) =>
    identical(this, other) ||
    qualified == other.qualified &&
    unqualified == other.unqualified &&
    capitalGainDistribution == other.capitalGainDistribution;

  num qualified = 0.0;
  num unqualified = 0.0;
  num capitalGainDistribution = 0.0;

  DividendBreakdown.empty();

  DividendBreakdown operator +(DividendBreakdown other) {
    return new DividendBreakdown(qualified + other.qualified,
        unqualified + other.unqualified,
        capitalGainDistribution + other.capitalGainDistribution);
  }
}
like image 612
user1338952 Avatar asked Jan 21 '26 07:01

user1338952


1 Answers

You can't, unless you also alter the behaviour of the + operator. The += operator and other compound assignment operators are simply shorthand for a normal operator and then an immediate assignment.

There is no way to extract extra information in the + operator to determine whether an assignment will be performed immediately or not, and therefore you must always return a new instance in case assignment is not being performed.

Instead, use your own method:

DividendBreakdown add(DividendBreakdown other) {
  //...
}
like image 122
Pixel Elephant Avatar answered Jan 23 '26 02:01

Pixel Elephant