Gregor
Gregor

Reputation: 3027

Dart: How to work around the diamond pattern with mixins?

Is there a way to solve the diamond problem when using Mixins in Dart? Have a look on the following simple example:

class M1 {
  String sayHello() => "hello M1";
}
class M2 {
  String sayHello() => "hello M2";
}
class S {
  String sayHello() => "hello S";
}
class C extends S with M1, M2 {}

main() {
  C c = new C();
  print(c.sayHello());
  print((c as M1).sayHello());
}

Output:

hello M2
hello M2

If you call "sayHello" on c, it depends on the order of the mixins in the class declaration of C, which of the implementations is executed. Always the implementation of the last mixin on the list is used. This is hardly explicit and might often be a matter of chance. Worse: The implementation of the superclass C is always hidden. The typecast doesn't change a thing, which of course is in accord with the general Dart philosophy that the runtime type doesn't come into play when executing code. Still it would be good if there were any means to explicitly decide between the different implementations. Is there such a possibility?

Upvotes: 3

Views: 1482

Answers (1)

lrn
lrn

Reputation: 71713

In short: No.

You can't solve a diamond problem in Dart because Dart doesn't have multiple inheritance, so it doesn't have the problem (or feature).

Adding mixins on top of a class is completely normal single inheritance, and Dart class implementation is always a single chain down to Object. The only thing mixins do is to allow the same members to occur in more than one chain.

That also means that there is no way to access overridden members higher in the chain. You can only ever access the top-most declaration, or, as a member function, the top-most declaration of your super-chain (using super.foo()).

Upvotes: 5

Related Questions