dart-lang / dart-lang/language

Generic method parameters need to be more tightly typed

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

Description

I've tried the following with Dart 2.15 and Dart 2.16.0-80.0.dev

I'm trying to create a typesafe method of the form:

```dart
void provide(Token token, T value) {
print(value);
}

void main()
{
/// This should be an error
provide(tokenInt, 'bad string');
}

class Token {}

final tokenInt = Token();

```

I'm expecting the call to 'provide', in main, to generate a compile error because tokenInt defines the type as int but I passed a string as the second argument.
Instead the code compiles and runs just fine.

Instead the user of my method is forced to write:

```dart
provide(tokenA, 'bad string');
```
This makes the code error prone as if they forget the type then they potentially end up with a runtime error.

My understanding from a stack overflow questions is that if the two arguments are not the same then dart searches the type tree to find a common parent.

If I wanted the types to be viable from some common base class I would expect to do something like:

```dart
void provide(T a, T b);
```

If I write:

```dart
void provide(T a, T b);
```
Then I would expect that both a and b must be of the same type.

The current design (If I've understood it correctly) seems to make adding type information to the method somewhat meaningless if you have more than one argument of the same type.

What I don't understand is what are the implications of tightening this rule against existing code bases.

Is there a particular reason for this behaviour or is it a left over from Dart 1.x.

I did try enabling strict-raw-types but this made no difference to the behaviour which surprised my somewhat as I would have expected it to require the call to `provide` to have a type argument added.

Contributor guide

Open the contributing guide

Research direction

No source file or test is named. Start with the generic method and Token examples in the issue, then read the Dart language specification on generic type inference and argument constraints; assess the compatibility implications of rejecting the mismatched call and document the resulting language-design decision.

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
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.