Mixins in Dart
Behavior stapled onto a class with with, no superclass claimed.
// A mixin is behavior without a superclass claim; with staples it on.
mixin Ringed {
String get band;
String describeBand() => 'wears band $band';
}
class Bird {
final String species;
Bird(this.species);
}
class StudyBird extends Bird with Ringed {
final String band;
StudyBird(super.species, this.band);
}
void main() {
final subject = StudyBird('reed warbler', 'RB-0207');
print('${subject.species} ${subject.describeBand()}');
}
How it works
mixin Ringeddeclares an abstractbandand a method using it.extends Bird with Ringedcombines base class and mixin.super.speciesforwards a constructor parameter up in one token.
Keywords and builtins used here
BirdRingedStringStudyBirdclassextendsfinalgetmixinsuperthisvoidwith
The run, in numbers
- Lines
- 20
- Characters to type
- 435
- Tokens
- 97
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 90 seconds.
Step 2 of 3 in Classes, step 14 of 27 in Language basics.