Skip to content

Instantly share code, notes, and snippets.

@ltOgt
Created December 27, 2021 09:56
Show Gist options
  • Save ltOgt/13aa3cd33c9dac1658a8069714589cdf to your computer and use it in GitHub Desktop.
Save ltOgt/13aa3cd33c9dac1658a8069714589cdf to your computer and use it in GitHub Desktop.
dart const

Using const constructors inside const constructors does not work

const MyClass(int x, y) : _offset = Offset(x,y);

Does not work because the call context is not currently propagated into the constructor body. Creating MyClass with const is different than creating it with new, but we can't pass that to Offset. Putting const before Offset is invalid in the new context, and having (implicit) new is invalid in const context. This might be changed in the future, and I saw there a quite a number of tickets with the tag enhanced-const. The intuitive behaviour would be that Offset is const when MyClass is const.

See dart-lang/language#2000 (comment)

Instance fields of const objects can not be guaranteed to be const

To me it feels natural to do something like

const a = A(value: 10);
const b = a.value;

This does not work since dart cant currently guarantee that value on A is a getter that returns a constant value:

class A { final int value; const A(this.value); }
final Random rng = Random()
class A2 implements A { get int value => rng.nextInt(); }

See dart-lang/language#1868 (comment) And also the proposal for stable getters, which seems like what one would expect to be the case already: dart-lang/language#1518

@ltOgt
Copy link
Author

ltOgt commented Jan 4, 2022

Cant use enum comparison in const expressions:
dart-lang/sdk#26980
dart-lang/language#1811

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment