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
B
require thatobjOfA
is aMixedA
by declaring it as:final MixedA objOfA;
If you can't unconditionally declare
objOfA
to be aMixedA
, perhaps you could makeB
generic and makeMixedB
require a specialized base type:class B<DerivedA extends A> { final DerivedA objOfA; const B(this.objOfA); } mixin MixedB on B<MixedA> { // ... }
Make
MixedB
perform 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
objOfA
will always be aMixedA
whenMixedB
is used (but you can't provide a static, compile-time guarantee), you could makeMixedB
overrideobjOfA
and cast it to aMixedB
:mixin MixedB on B { @override MixedA get objOfA => super.objOfA as MixedA; void someMethod() { objOfA.someNewMethod(); } }