Home > Mobile >  How to use restricted mixin to an interface with implementation of that interface at same time in da
How to use restricted mixin to an interface with implementation of that interface at same time in da

Time:04-08

What I have:

  1. Interface (InterfaceA) with a method that must be overridden.
  2. Restricted to interface mixin (MixinB) with a method that I want to use without overriding.
  3. Class (ClassC) with implementation of interface and usage of mixin.

Question: Is it possible to use restricted mixin to interface with implementation of that interface at the same time?

Code below is an example and shows how I ideally want to use mixin and interface

abstract class InterfaceA {
  int getValue();
}

mixin MixinB on InterfaceA {
  int getPreValue(int i) => i;
}

// Error:
// 'Object' doesn't implement 'InterfaceA' so it can't be used with 'MixinB'.
class ClassC with MixinB implements InterfaceA {
  @override
  getValue() => getPreValue(2);
}

CodePudding user response:

Your mixin doesn't need to be used on a class of type InterfaceA. You could declare it as

mixin MixinB implements InterfaceA {
  in getPrevAlue(int i) => i;
}

instead. Then using the mixin will require the mixin application class to implement InterfaceA, because the mixin doesn't provide the implementation, but the it can do so before or after mixing in the mixin. Then your code would just be:

class ClassC with MixinB { // no need for `implements InterfaceA`
  @override
  getValue() => getPreValue(2);
}

Only use an on requirement on a mixin if you need to call a super-interface member on the on type(s) using super.memberName. Otherwise just use implements to ensure that the resulting object will implement that interface. You can still do normal virtual calls on the interface.

Example:

abstract class MyInterface {
  int get foo;
}
mixin MyMixin implements MyInterface {
  int get bar => this.foo; // Valid!
}
class MyClass with MyMixin {
  @override
  int get foo => 42;
  int useIt() => this.bar; // returns 42
}
  • Related