[Share] Interesting behaviour for mixin

Hi I would like to share an interesting behaviour below:
See the code:

mixin EggLayer {
  void layEggs() {
    print('Plop plop');
  }
}
  
mixin Flyer {
  void fly() {
    print('Swoosh swoosh');
  }
}
  
abstract class Bird {
  void fly() {
    print("parent parent");
  }
  void layEggs();
}

class Robin extends Bird with EggLayer, Flyer {
  @override
  void fly() {
    super.fly();
    print("child child");
  }
}

In main:

final robin = Robin();
robin.fly();
robin.layEggs();
// output below:
// Swoosh swoosh
// child child
// Plop plop

Explanation:

  • The fly method in mixin has shadowed over the fly method in Robin class.
2 Likes

Let me filter out the egg laying code since it doesn’t apply to the interesting behavior:

void main() {
  final robin = Robin();
  robin.fly();
  // Swoosh swoosh
  // child child
}


mixin Flyer {
  void fly() {
    print('Swoosh swoosh');
  }
}

abstract class Bird {
  void fly() {
    print("parent parent");
  }
}

class Robin extends Bird with Flyer {
  @override
  void fly() {
    super.fly();
    print("child child");
  }
}

You’ve got three separate implementations of fly. Normally super.fly() would print “parent parent”, but the mixin overrides the parent method. However, the mixin doesn’t override the child method. That is interesting.

I like how you’re exploring the edges of the language. Good job.

2 Likes

@suragch thank you for your appreciation. I don’t intent to test it like that at the first reading. But when I try to write the notes for mixin section, the idea of using super.fly() suddenly pop up in my head. So, that’s the origin of coming up this idea.

2 Likes

Dear @ellery

We hope that the response provided by @suragch was helpful in addressing your concerns.

If you have further questions or need additional assistance, please don’t hesitate to ask. Our community is here to support you!