dart-lang / dart-lang/language

Type promotion fails with null checks in Iterable.where()

Open
#1,606 3 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

If you have an `Iterable` and wish to filter it to an `Iterable` which only contains the non-null elements, using `Iterable.where()` does not end up promoting the type of `E?`.

For example, when processing an XML document, the following code

```
Iterable files = xmlElements
.map((XmlElement element) => element.getAttribute('href'))
.where((String? href) => href != null)
.map((String href) => File(path.dirname(xmlFile.path) + href));
```
results in the following error from the Dart Analyzer:`error: The argument type 'File Function(String)' can't be assigned to the parameter type 'dynamic Function(String?)'.`

It is worth noting that this approach does correctly promote the type.
```
Iterable files = xmlElements
.map((XmlElement element) => element.getAttribute('href'))
.whereType()
.map((String href) => File(path.dirname(xmlFile.path) + href));
```

However, I don't think all use cases are necessarily as easily worked around. The addition of an `Iterable.whereNotType()` would make cases of mixed-content Iterables easier to filter (`Iterable.whereType()` should be equivalent to that, but is clunkier to read the intent of I think). A need to filter to elements of either `A` OR `B` however, would necessitate the use of `Iterable.where()` without a ready type-promoting alternative that I can see.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the Dart Analyzer error with the Iterable, where((String? href) => href != null), and map((String href) => ...) example. Compare it with the working whereType() example and review the discussion around type promotion and a possible whereNotType(). Done means the intended behavior or language change is clearly specified and the analyzer accepts the supported pattern.

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.