-1

The following code got error Error: Cannot invoke a non-'const' constructor where a const expression is expected.:

class TestConst {
  final num x;
  final num y;
  TestConst(this.x, this.y);
}


void main() {

  TestConst myconst1 = const TestConst(1,2);
  TestConst myconst2 = const TestConst(1,2);

  print(identical(myconst1, myconst2));

}

while the following didn't, and strangely identical(myconst1, myconst2) return false when TestConst indeed only has const-constructor? :

class TestConst {
  final num x;
  final num y;
  const TestConst(this.x, this.y);
}


void main() {

  TestConst myconst1 = TestConst(1,2);
  TestConst myconst2 = TestConst(1,2);

  print(identical(myconst1, myconst2));

}
NeoZoom.lua
  • 2,269
  • 4
  • 30
  • 64

1 Answers1

2

const on a constructor means that the constructor can create a const object (if the callsite opts in and if all of the construction arguments are also const), not that it only creates const objects.

The Language Tour does mention this (but not in much detail):

Constant constructors don’t always create constants. For details, see the section on using constructors.

...

Some classes provide constant constructors. To create a compile-time constant using a constant constructor, put the const keyword before the constructor name:

And if you're wondering why a constructor declared with const still needs const to be explicitly specified when invoked, see: Dart: Is there a disadvantage to using const constructor?

jamesdlin
  • 81,374
  • 13
  • 159
  • 204