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);
}
}
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) {
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With