dart-lang / dart-lang/language

const extensions / `constexpr` in Dart

Open
#3,722 1 comment 6 reactions 0 assignees View on GitHub
feature
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

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

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

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

```dart
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:

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

Which would de-sugar into the usual:

```dart
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.

Contributor guide

Open the contributing guide

Research direction

Start by reading the proposal and the referenced issue #2222; the payload names no source files, tests, or entry points. Done would require a language-design decision on const extension getters or constexpr-like syntax, followed by an agreed specification and implementation plan.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.