typestar

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

  1. Sighting(this.species, this.count) declares and assigns at once.
  2. Sighting.single is a named constructor delegating with : this(...).
  3. @override toString makes the object print itself.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Classes, step 13 of 27 in Language basics.

← Previous Next →