Search code examples
dartmixins

Dart: mixin composition without extension


I understand Dart mixins must not extend other classes. However, is there some way to create a composition of two mixins in some way that doesn't use an extend? For example, consider the following code

abstract class GreeterMixin{
  sayHello(String person) => print("Hello $person");
}

abstract class SmallTalkerMixin implements GreeterMixin{
  makeSmallTalk(String person){
    sayHello(person);
    print("The weather looks good");
  }
}

class Animal{
  final int nLegs;
  Animal(this.nLegs);
}

class Person extends Animal{
  final String name;
  Person(this.name): super(2);
}

class SocialPerson extends Person with GreeterMixin, SmallTalkerMixin{
  SocialPerson(String name): super(name);

  introduceSelf(String person){
    makeSmallTalk(person);
    print("My name is $name");
  }
}

Clearly, a smallTalker must be a greeter, but because I want to use SmallTalkerMixin as a mixin, it cannot extend GreeterMixin. Unfortunately, this means that everywhere I include SmallTalkerMixin as a mixin, I must also include GreeterMixin as a mixin.

In other words, is there a way to acheive the following using just the code above?

abstract class SmallTalkerGreeterMixin implements SmallTalkerMixin, GreeterMixin{
  sayHello(String person) => print("Hello $person");

  makeSmallTalk(String person){
    sayHello(person);
    print("The weather looks good");
  }
}

Solution

  • I don't think this is currently possible. Many limitations of mixins are supposed to be removed but there is no specific time frame until when this will happen.