antonin.lebrard
antonin.lebrard

Reputation: 139

Can it be possible to have an operator working with the precedent value in an operation

I know that a single operator should not, and cannot be usable in both "directions". But I would like to know if there is an operator for each directions, and which one I miss. My question is way more simple to explain with an example, so here it is :

void main(){
  int i = 1;
  Test y = new Test(2);
  print(y+i); // Working, print 3
  print(i+y); // Not working crash, I would like this to work
}

class Test {
  dynamic _data;
  Test(value) : this._data = value;
  operator+(other) => _data + value;
  toString() => _data.toString();
}

So as I cannot add an operator in the class int, is there an other operator to implement in the class Test to support this operation.

Upvotes: 1

Views: 31

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657741

The simple answer is "no". You can only add a num (int or double) to int.

If the result should be an int you can add an int getter

class Test {
  dynamic _data;
  Test(value) : this._data = value;
  operator+(other) => _data + value;
  toString() => _data.toString();
  int asInt => _data;
}

print(i+y.asInt);

which is a bit dangerous in this case because _data is dynamic.

You could use generics

class Test<T> {
  T _data;
  Test(this._data);
  operator+(other) => _data + value; // 
  toString() => _data.toString();
  T asBaseType => _data;
}

Upvotes: 1

Related Questions