Created
February 11, 2019 10:40
-
-
Save rhcarvalho/9745b0f73157959a1c82a66ddf8fdba4 to your computer and use it in GitHub Desktop.
Dart constructors are not really functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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