Dart
Summary - Mixins
Combine mixin, with and on to write a capability system.
Summary - Mixins
In this group you saw all the tools of mixins: mixin, with, on, multiple mixins and mixin vs inheritance. Now we will merge them in a capability system.
A capability system adds reusable behaviors to different classes. For example, a Bird class applies both the Flyer and the Walker mixin; both capabilities are reachable on an instance. In the second step we add one more capability and equip the Duck class with three mixins. This shows the power of mixins in one example.
Exercise Add two capabilities to Bird
Define two mixins named Flyer and Walker. In Flyer add a void fly() { print('Flying'); } method, in Walker add a void walk() { print('Walking'); } method. Write a class named Bird: class Bird with Flyer, Walker { Bird(); }. In main, create an instance with var b = Bird(); and call b.fly() and b.walk().
Show example solution
// Define the Flyer and Walker mixins
mixin Flyer {
void fly() {
print('Flying');
}
}
mixin Walker {
void walk() {
print('Walking');
}
}
class Bird with Flyer, Walker {
Bird();
}
void main() {
var b = Bird();
b.fly();
b.walk();
}
Third capability: Swimmer
In the second step we add a third mixin to the capability system: Swimmer. The Duck class will apply all three mixins at once and gain a set of capabilities: flying, walking and swimming.
Example: class Duck with Flyer, Walker, Swimmer { Duck(); }. The three mixins are separated by commas. A Duck instance can call fly(), walk() and swim() all together. This shows the real power of mixins: capabilities are defined one by one, applied together to a class; behavior grows without expanding the inheritance tree.
Exercise Add a third mixin to Duck
Keep the existing Flyer and Walker mixins. Add a third mixin named Swimmer; write a void swim() { print('Swimming'); } method. Define a class named Duck: class Duck with Flyer, Walker, Swimmer { Duck(); }. In main, create an instance with var d = Duck(); and call d.fly(), d.walk() and d.swim().
Show example solution
mixin Flyer {
void fly() {
print('Flying');
}
}
mixin Walker {
void walk() {
print('Walking');
}
}
mixin Swimmer {
void swim() {
print('Swimming');
}
}
class Duck with Flyer, Walker, Swimmer {
Duck();
}
void main() {
var d = Duck();
d.fly();
d.walk();
d.swim();
}
Test yourself
-
Which is true for a capability system?
- Each capability needs its own base class
- Each capability is a mixin; applied to classes with with
- Capabilities are added only with static fields
- Capabilities are written inside the constructor
Show answer
Each capability is a mixin; applied to classes with with — Mixin + with is the core of a capability system.
Next lesson: Generic class