typestar

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

  1. mixin Ringed declares an abstract band and a method using it.
  2. extends Bird with Ringed combines base class and mixin.
  3. super.species forwards a constructor parameter up in one token.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Classes, step 14 of 27 in Language basics.

← Previous Next →

Mixins in other languages