Reputation: 511558
I created a const class like so:
class MyClass {
const MyClass(this.x, this.y);
final double x;
final double y;
MyClass operator +(MyClass other) {
return MyClass(x + other.x, y + other.y);
}
}
Now if I try to create a new class by adding two const
values:
const objectA = MyClass(1, 4);
const objectB = MyClass(3, 2);
const objectC = objectA + objectB;
I get an error:
In constant expressions, operands of this operator must be of type 'num'.
If I use final
it works, though:
final objectC = objectA + objectB;
I was going to say it's because the operator overload method creates a new class at runtime, but objectA
and objectB
were also created at runtime and they're constants. So why can't Dart allow objectC
to be const
?
Upvotes: 1
Views: 429
Reputation: 34
There is currently no way to define a constant operator that accepts and returns classes other than num
in Dart.
You cannot use these operators as constant expressions, unless it only accepts and returns the type num
.
Dart cannot ensure that the expression is actually constant.
To be more precise, what this error actually means is "The operator you are calling is not constant."
Upvotes: 0