dart-lang / dart-lang/language
Unexpected generic inference only on `async` functions
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
We recently ran into a weird situation where calling a method with a `?.` operator yielded an unexpected inferred generic type in `async` functions. This snippet highlights the issue:
```dart
class Box {
final Object _value;
Box(this._value);
T read() {
print(T);
return _value as T;
}
}
int? _readIntSync(Box? box) {
return box?.read(); // works: The `T` in `read` is inferred as `int`
}
Future _readIntAsync(Box? box) async {
return box?.read(); // does not work: The `T` in `read` is inferred as `Never`
}
void main() {
final box = Box(3);
_readIntSync(box); // goes through
_readIntAsync(box); // eventually throws a cast error
}
```
I would have expected type inference to infer `T` as `int` in both cases for the two methods. This is confusing to me since I don't see a compelling reason for inference to behave differently in the two cases.
Apologies if this is working as intended (in which case I'll probably file a language issue instead?).
Contributor guide
Research direction
Start with the Dart reproduction in the issue and compare the synchronous and asynchronous calls to read(). Trace the language's generic type-inference rules for nullable calls in async functions; done means determining whether the differing inference is intended and specifying the required language change if it is not.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100