Home > Software engineering >  How to use a mixin-ed method of a class in another mixin of another class
How to use a mixin-ed method of a class in another mixin of another class

Time:09-28

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 that objOfA is a MixedA by declaring it as: final MixedA objOfA;

  • If you can't unconditionally declare objOfA to be a MixedA, perhaps you could make B generic and make MixedB 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 a MixedA when MixedB is used (but you can't provide a static, compile-time guarantee), you could make MixedB override objOfA and cast it to a MixedB:

    mixin MixedB on B {
      @override
      MixedA get objOfA => super.objOfA as MixedA;
    
      void someMethod() {
        objOfA.someNewMethod();
      }
    }  
    
  •  Tags:  
  • dart
  • Related