Skip to content

Allow passing constructors as functions #216

Closed
@vsmenon

Description

@vsmenon

Support tearing-off and passing constructors similar to current support for functions. Example:

class Text {
  String label;
  Text(this.label);
}

void main() {
  // Tear-off the `Text` constructor and pass it to the `map` function.
  List<Text> l = ['foo', 'bar', 'baz'].map(Text.new).toList();

  // Print all text labels.
  for (var t in l) {
    print(t.label);
  }
}

Original issue filed by @rhcarvalho on February 11, 2019 10:59 as dart-lang/sdk#35901

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: [
      Heading('Children:),
      ...['Alice', 'Bob', 'Charlie'].map(Text.new),
    ]
  );

What I have to write instead with Dart 2.1.0:

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

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions