I have class B which has object of class A as a member field.
And I want to access the new mixin-ed method of class A in the mixin-ed method for class B. I tried the following but it doesn't work.
https://dartpad.dev/?id=2af929e713c46e9b853aee84f4407007&null_safety=true
class A {}
class B {
final A objOfA;
const B(this.objOfA);
}
mixin MixedA on A {
void someNewMethod() {
// do something
}
}
mixin MixedB on B {
void someMethod() {
objOfA.someNewMethod(); // <-- error
}
}
CodePudding user response:
mixin MixedB on B means that classes that use MixedB are known only to derive from B. Class B provides no guarantee that its objOfA member is an instance of MixedA. Some of your options:
Make
Brequire thatobjOfAis aMixedAby declaring it as:final MixedA objOfA;If you can't unconditionally declare
objOfAto be aMixedA, perhaps you could makeBgeneric and makeMixedBrequire a specialized base type:class B<DerivedA extends A> { final DerivedA objOfA; const B(this.objOfA); } mixin MixedB on B<MixedA> { // ... }Make
MixedBperform a runtime check:mixin MixedB on B { void someMethod() { final objOfA = this.objOfA; if (objOfA is MixedA) { objOfA.someNewMethod(); } } }If you can personally guarantee that
objOfAwill always be aMixedAwhenMixedBis used (but you can't provide a static, compile-time guarantee), you could makeMixedBoverrideobjOfAand cast it to aMixedB:mixin MixedB on B { @override MixedA get objOfA => super.objOfA as MixedA; void someMethod() { objOfA.someNewMethod(); } }
