dart-lang / dart-lang/language

Adapt a generic type based on a potentially null value

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

Description

We should be able to adapt an inferred generic type for based on a potentially `null` value.

## Example

Here is an example where a class stores an object and provides a particular transform of that object:
```dart
class MyView {
final T object;
final View Function(T object) _view;

MyView({
required this.object,
View Function(T object)? view,
}) : _view = view ?? ((v) => v);

View view() => _view(object);
}
```

This is currently showing the following error: `The return type 'T' isn't a 'View', as required by the closure's context.`

I am trying to provide a default identity transform when `view` passed to constructor is `null` (in that case, `View` should be `T`).

**Note**: Here `T` is not always `View`. For example, the object could be an `int` and the `view` could be `(n) => n.toString()`. However, when `view` is left `null` I would like `View` to be an `int`.

Dart should adapt the inferred type for `View` to `T` when `view` is `null`.

Contributor guide

Open the contributing guide

Research direction

Start with the generic MyView constructor example in the issue and review Dart's generic type inference and null-aware context rules. Determine how inference should behave when view is null versus when it is a transforming function. Done means the intended inference behavior is specified clearly enough to support implementation and language 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.