Classes and constructors in Dart
this. sugar assigns fields; named constructors add doors.
class Sighting {
final String species;
final int count;
// this. in the parameter list assigns fields directly; a named
// constructor offers a second way in.
Sighting(this.species, this.count);
Sighting.single(String species) : this(species, 1);
@override
String toString() => '$count x $species';
}
void main() {
final flock = Sighting('lapwing', 60);
final loner = Sighting.single('kingfisher');
print(flock);
print(loner);
}
How it works
Sighting(this.species, this.count)declares and assigns at once.Sighting.singleis a named constructor delegating with: this(...).@override toStringmakes the object print itself.
Keywords and builtins used here
SightingStringclassfinalintthisvoid
The run, in numbers
- Lines
- 19
- Characters to type
- 431
- Tokens
- 95
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 81 seconds.
Step 1 of 3 in Classes, step 13 of 27 in Language basics.