user1338952
user1338952

Reputation: 3391

How to make an efficient operator+=

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);
  }
}

Upvotes: 3

Views: 102

Answers (3)

JAre
JAre

Reputation: 4756

You can solve efficiency problem from the another perspective. For example, if you have two huge complex collections and + operator will combine them into to the new one, it could be slow. But instead of directly combine those collections and creating new one, you can implement special collection view that will represent combination of them and perform heavy tasks 'on-demand' in a lazy style.

Upvotes: 0

Pixel Elephant
Pixel Elephant

Reputation: 21403

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) {
  //...
}

Upvotes: 3

Pawel Uchida-Psztyc
Pawel Uchida-Psztyc

Reputation: 3838

You can return this (or other) if you'd like to:

class Point {
  int x;
  int y;
  Point(this.x, this.y);
  Point operator +(Point other){
    this.x = x + other.x;
    this.y = y + other.y;
    return this;
  }
  String toString(){
    return "Point: x: $x, y: $y";
  }
}

And usage:

Point p1 = new Point(1,1);
Point p2 = new Point(2,2);
print((p1+p2));

Result with: Point: x: 3, y: 3

Upvotes: -1

Related Questions