Dart overriding unary minus operator

Issue

As per Language specs (10.1.1 Operators) I am trying to override some operators.

I get an analyzer error when overriding the ‘minus’ and ‘unary minus’ operators – one that I don’t get:

‘The operator “-” is not defined on class Indentation’

but in the class I have defined it:

  Indentation operator -() {
    level--;
    return this;
  }

and I use it like myInstance--; and it actually does work, but still the analyzer complains and I cannot submit the code ‘clean’ because of the error.

I have looked up an old thread (Why does overriding negate cause static warning in Dart) but I think it is not relevant here.

Any advise is welcome.

Solution

--x is the same as x -= 1. To use it you have to define the operator -(p) (not operator -())

Indentation operator -(n) => new Indentation(level - n);

Answered By – Alexandre Ardhuin

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.