Skip to content

Instantly share code, notes, and snippets.

@rhcarvalho
Created February 11, 2019 10:40
Show Gist options
  • Save rhcarvalho/9745b0f73157959a1c82a66ddf8fdba4 to your computer and use it in GitHub Desktop.
Save rhcarvalho/9745b0f73157959a1c82a66ddf8fdba4 to your computer and use it in GitHub Desktop.
Dart constructors are not really functions
class Greeter {
final String name;
Greeter(this.name);
Greeter.withName(this.name);
static Greeter staticWithName(String name) {
return Greeter(name);
}
void greet(String who) {
print('${name} says: Hello ${who}!');
}
}
void main() {
final g = Greeter('Dartinius');
/// It is fine to pass an instance method as a function:
['John', 'Mary', 'Bob', 'Alice'].forEach(g.greet);
/// However, one cannot pass a constructor as function:
//['John', 'Mary', 'Bob', 'Alice'].map(Greeter).forEach((Greeter g) => g.greet('World'));
/// Neither a named constructor:
//['John', 'Mary', 'Bob', 'Alice'].map(Greeter.withName).forEach((g) => g.greet('World'));
/// Instead, a static method would work, and from the call site it looks the same as a named constructor:
['John', 'Mary', 'Bob', 'Alice'].map(Greeter.staticWithName).forEach((g) => g.greet('World'));
/// Alternatively, one may use an anonymous function to wrap the constructor:
['John', 'Mary', 'Bob', 'Alice'].map((String s) => Greeter(s)).forEach((g) => g.greet('Universe'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment