dart-lang / dart-lang/language

Allow Iterators To Use The for-in Syntax

Open
#3,979 5 comments 0 reactions 0 assignees View on GitHub
request
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

An `Iterator` should be able to use the "for-in" syntax like an `Iterable`.

This should work:
```dart
for (final e in iterator) {
// code
}
```
Instead of having to do
```dart
while (iterator.moveNext()) {
final e = iterator.current;
// code
}
```
This is syntactically better, especially when you add iterator specific methods/chaining. Assume an `extractIf` method that returns an `Iterator`. This should work:
```dart
List numbers = [1, 2, 3, 4, 5];

for (final e in numbers.extractIf((element) => element % 2 == 0)) { // 2, 4
// code
}
// numbers == [1, 3, 5]
```
Rather than having to do:
```dart
List numbers = [1, 2, 3, 4, 5];

Iterator iterator = numbers.extractIf((element) => element % 2 == 0);
while (iterator.moveNext()) {
final e = iterator.current;
// code
}
```
Of course you can always wrap the `Iterator` in an `Iterable`, but the normal convention for an `Iterable` variable is that it can be looped multiple times without a side effect. The nice thing about `Iterator` is that it can only be consumed once. If `extractIf` returned an `Iterable` it would go against the default developer expectation, which may lead to it being misused - e.g. being passed to another function that takes and `Iterable` and that function will iterate that iterable more than once.

## Possible Solution

Anything that implements `IteratorProvider` can be used in a "for-in" loop.
```dart
abstract class IteratorProvider {
Iterator get iterator;
}
```
`Iterable` already fulfills this interface and `Iterator` can just add
```dart
Iterator get iterator => this;
```
The other nice effect of this approach is methods can be designed to take an `IteratorProvider` instead of an `Iterator`, which allows making methods more generic over an `Iterable` or `Iterator`.

Edit:
Another possible named could be `Iter` rather than `IteratorProvider`, as `Iter` is the prefix to both `Iterable` and `Iterator`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.