dart-lang / language

Design of the Dart language
Other
2.66k stars 205 forks source link

const extensions / `constexpr` in Dart #3722

Open techvx opened 5 months ago

techvx commented 5 months ago

Consider a case in which one may want to instantiate a given const instance, in different places, a few too times too many:

const d = Duration(milliseconds: 250); // <--
withDuration(d); // ...

After a (short) while, one may attempt to reach for a short-hand, such as:

extension DuranDurat on int {
  get Duration minutes => Duration(minutes: this);
  get Duration secs => Duration(seconds: this);
  get Duration ms => Duration(milliseconds: this);
}

This one, however - would no long evaluate at compile time.

Having a:

extension ConstDurat on int {
  const get ms => Duration(milliseconds: this);
}

Which would de-sugar into the usual:

const Duration(milliseconds: ...)

at every invocation inline, would be rather useful indeed. The C++/like constexpr were brought up already at #2222, yet I don't see much discussion around it. Low priority as it might be, it wouldn't hurt the language in the slightest.

mnordine commented 5 months ago

Dupe of https://github.com/dart-lang/language/issues/663