dart-lang / dart-lang/language
Allow refutable patterns in assignment patterns.
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
Dart distinguishes between declaration patterns, assignment patterns and matching patterns, where only matching patterns are allowed to be refutable. It makes sense that declaration patterns must be irrefutable, otherwise the declared variables cannot be accessible.
Assignment patterns, on the other hand, could be allowed to be refutable, making it a *conditional assignment*.
If it doesn't match, the variables still exist, they just didn't change value. A refutable assignment cannot promote, since it may do nothing, but it can be shorter than what you'd otherwise need for a conditional assignment.
Take (real code):
```dart
... (Object error, StackTrace? stackTrace) {
AsyncError? replacement = Zone.current.errorCallback(error, stackTrace);
if (replacement != null) {
AsyncError(:error, :stackTrace) = replacement;
}
// ...
```
If the pattern could be refutable, this could just be:
```dart
AsyncError(:error, :stackTrace)? = Zone.current.errorCallback(error, stackTrace);
```
which assigns nothing if the value is `null`.
This has quite a pitfall, though, in that mistyping a type will not be an error, just a weird no-op.
If I forgot the `AsyncError` and wrote `(:error, :stackTrace)? = ...`, the value would not be a record, and so the patter is refuted and nothing happens.
So, maybe we should only allow `?`, or just not any unrelated type.
(It would make sense to have `Sub(subField: variable) = super;` instead of `if (super case Sub(:subField)) variable = subField;`.)
Maybe it's a bad idea, but it would make this one code pattern easier.
Maybe we should just have a way to bail further out on a null-check, past more than a selector chain.
Contributor guide
Research direction
Start by reading the issue's discussion of declaration, assignment, and matching patterns, including the conditional-assignment examples. The work is not yet defined: it would need a settled decision on whether refutable assignment patterns should be supported and what restrictions or alternative null-check behavior should count as done.
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
- Needs clarification
- Newbie friendliness
- 25/100