dart-lang / language

Design of the Dart language
Other
2.65k stars 202 forks source link

Support templated functions as function literals #103

Open jyaif opened 5 years ago

jyaif commented 5 years ago

For example, the following code does not compile:

void foo<T>(T v) {
  print(v);
}

void main() {
  <int>[10,20,30].forEach(foo<int>); // <= does not compile
  <int>[10,20,30].forEach((int v) => foo<int>(v)); // <= triggers avoid_function_literals_in_foreach_calls and unnecessary_lambdas warnings.
}
eernstg commented 5 years ago

It is true that we do not (yet) have the syntactic support for creating a non-generic function from a generic function by passing the type arguments (and not the value arguments). But we do have an implicit mechanism doing just that:

void foo<T>(T v) {
  print(v);
}

void main() {
  <int>[10,20,30].forEach(foo); // (1).
}

At (1), we implicitly obtain a function of type void Function(int) as a 'generic function instantiation' from the generic function foo. For more details, please consult the feature specification for that mechanism.