dart-lang / dart-lang/language

Allow non-const classes to be more efficient on const values

Open
#187 3 comments 0 reactions 0 assignees View on GitHub
enhanced-const
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

There are cases where we would like to do defensive copying only when a value is not `const`.

For example, an immutable list implementation might take a `List` as input. If the `List` is not `const`, it needs to make a defensive copy.

Currently only something that is itself `const` can be sure to receive `const` values. This is very restrictive. Lots of immutable collections, for example, use mutable internals for efficiency.

What is requested, then, is a way for non-`const` classes to know whether a value is `const` and behave differently. One feature that would satisfy this would be a way to specify an alternative constructor that is used when the values passed in are `const`:

```dart
class ImmutableList {
final List list;

// This will be called if `list` is `const`.
ImmutableList(const List list) : this.list = list;

// This will be called if `list` is not `const`.
ImmutableList(List list) : this.list = list.toList();
}
```

Further, 'auto const' would apply in these contexts, allowing:

```
ImmutableList([1, 2, 3])
```

to allocate a `const` list and avoid copying altogether.

The idea is just for illustration--the request is to give a way to avoid defensively copying `const` values.

Thanks!

Contributor guide

Open the contributing guide

Research direction

No files, tests, or entry points are named. Start by studying the requested const-value detection and alternative-constructor behavior in the issue body, including the defensive-copying and auto-const examples. Done means defining a language design that lets non-const classes avoid copying const values.

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
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.