dartenumscode-reuseimplements

Is there a way in Dart to reuse method implementation in multiple Enums?


I want to create 2 Enums (or even more later on) with a same field, and a same method relating to it, like:

enum Enum1 {
  A1('A1', 1),
  B1('B1', 2);

  String name;
  int x1;
  Enum1(this.name, this.x1);

  String concat(String s) {
    return name + s;
  }
}

enum Enum2 {
  A2('A2', 3),
  B2('B2', 4);

  String name;
  int x2;
  Enum2(this.name, this.x2);

  String concat(String s) {
    return name + s;
  }
}

What should I do to reuse the code of identical methods in different Enums?

Namely, how can I reuse the codes related to name and concat in the previous example?

I have tried to use a class to do implementation for both Enums, but it kept prompting me that I have to re-implement the concat method and the getter of name respectively in each Enum.

My failed attempt is like:

class Reuse {
  String name;
  String concat(String s) {
    return name + s;
  }
}

enum Enum1 implements Reuse {
  A1('A1',1), B1('B1',2);

  int x1;
  String name;
  Enum1(this.name, this.x1);

  String concat(String s);
}

enum Enum2 implements Reuse {
  A2('A2',3), B2('B2',4);

  int x2;
  String name;
  Enum2(this.name, this.x2);

  String concat(String s);
}

Solution

  • This can be achieved by declaring Reuse as a mixin, and declaring the enums as with Reuse rather than implements Reuse.

    The implements keyword does not inherit the implementation of methods while extends and with do give you the implementation of the methods. And since enums in dart are restricted from using extends, this leaves with as the only option, and you can only use with with mixins.

    mixin Reuse {
      String get name;
      String concat(String s) {
        return name + s;
      }
    }
    
    enum Enum1 with Reuse {
      A1('A1', 1),
      B1('B1', 2);
    
      final int x1;
      final String name;
      const Enum1(this.name, this.x1);
    }
    
    enum Enum2 with Reuse {
      A2('A2', 3),
      B2('B2', 4);
    
      final int x2;
      final String name;
      const Enum2(this.name, this.x2);
    }
    
    void main() {
      print(Enum1.A1.concat('example'));
      print(Enum2.A2.concat('example'));
    }