New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: allow passing constructors as functions #35901

Closed
rhcarvalho opened this Issue Feb 11, 2019 · 1 comment

Comments

Projects
None yet
2 participants
@rhcarvalho
Copy link
Contributor

rhcarvalho commented Feb 11, 2019

This feature request intends to allow using constructors where functions with the same type/signature are expected.

Example code: https://dartpad.dartlang.org/9745b0f73157959a1c82a66ddf8fdba4


Background

As of Dart 2, Effective Dart suggests not using the new keyword and removing it from existing code.
Doing that makes named constructors and static methods look the same at call sites.

The Language Tour says (emphasis mine):

Constructors

Declare a constructor by creating a function with the same name as its class [...]

Thus suggesting that a constructor is a function. But it turns out it is not really a function, as it cannot be used in all contexts where a function can.

Why it would be useful

Dart built in types, in particular collection types, have several methods that take functions as arguments, for instance .forEach and .map, two concise and expressive ways to perform computations.

In an program I'm working on, I got a bit surprised by not being able to create new instances using Iterable.map + a named constructor. And then I realized that others have arrived at the same conclusion at least 4 years back on StackOverflow, but I could not find a matching issue.

Example Flutter code

What I would like to write:

  return Column(
    // This won't compile:
    children: ['Alice', 'Bob', 'Charlie'].map(Text).toList(),
  );

What I have to write instead with Dart 2.1.0:

  return Column(
    // Need a dummy wrapper around the constructor:
    children: ['Alice', 'Bob', 'Charlie'].map((name) => Text(name)).toList(),
  );

Note that the feature request is not specific to Flutter code, but applies to any Dart code as per the more generic example in https://dartpad.dartlang.org/9745b0f73157959a1c82a66ddf8fdba4.


  • Dart SDK Version (dart --version)
Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)
@vsmenon

This comment has been minimized.

Copy link
Member

vsmenon commented Feb 11, 2019

This issue was moved to dart-lang/language#216

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment