Last active
October 8, 2019 03:18
-
-
Save kirkdrichardson/fc100517efced76881fd0d8d37f673a8 to your computer and use it in GitHub Desktop.
Constructors in Dart
This file contains hidden or 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
// Constructors in Dart (as of v2.5) | |
// This example can be run at https://dartpad.dartlang.org/fc100517efced76881fd0d8d37f673a8 | |
// For other examples see https://gist.github.com/kirkdrichardson | |
void main() { | |
// Use the default constructor | |
final Car c = Car(); | |
print('Car with default constructor id: ${c.id}'); | |
print('\n\n'); | |
// Use the parameterized constructor | |
final CarParam cp = CarParam(42); | |
print('Car with parameterized constructor id: ${cp.id}'); | |
print(''); | |
// Use the named constructor | |
final CarParam cNamed = CarParam.myNamedConstructor(99, 'Toyota'); | |
print('Car with named constructor id: ${cNamed.id} AND... name: ${cNamed.name}'); | |
} | |
// Default constructor | |
class Car { | |
int id; | |
Car() { | |
print('Ran default constructor'); | |
} | |
// 🚫Expect Error --> "The default constructor is already defined." | |
// You can only have EITHER the default or a parameterized constructor. 🤯 | |
// For multiple constructors, see named constructor usage below. 🙌 | |
// Car(id) { | |
// this.id = id; | |
// } | |
} | |
class CarParam { | |
int id; | |
String name; | |
// Paramaterized constructor. | |
CarParam(int id) { | |
print('Ran paramaterized constructor.'); | |
this.id = id; | |
} | |
// To have multiple constructors, we can use named constructors, e.g. | |
CarParam.myNamedConstructor(int id, String name){ | |
print('Ran named constructor.'); | |
this.id = id; | |
this.name = name; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment