dart-lang / dart-lang/language
Safe list destructuring
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
Let's say I have a variable called `list` that stores, you guessed it, a list of items.
```dart
final list = ['a', 'b'];
```
For this example, we're always going to assume that list at least has a length of 1. When we need to safely access the second value in the list though, it's kind of annoying.
```dart
final a = list.first;
final b = list.elementAtOrNull(1);
```
Here are some proposed syntax additions that can help make it easier to safely access list items:
```dart
final [a, b?] = list; // b would be null if the list doesn't have enough items
```
For the syntax below, you can specify default values, but they must be a subtype of the inferred list type. So `list` is inferred as `List` so you can do default values of type `String?`.
Using `else`:
```dart
final [a, b else null] = list;
final [a, b else 'b'] = list;
```
Using `??`:
```dart
final [a, b ?? null] = list; // looks odd but could work, reads as if not present, use null
final [a, b ?? 'b'] = list;
```
Default value syntax used in constructors:
```dart
final [a, b = null] = list;
final [a, b = 'b'] = list;
```
Contributor guide
Research direction
Start by reviewing the proposed safe list destructuring forms and the existing Dart pattern syntax relevant to list access. Done would require selecting and specifying one syntax with its behavior for short lists and default values; this issue names no implementation files or tests.
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
- 30/100