Search code examples
mixinsdart

Does Google Dart support mixins?


I've skimmed through the language documentation and it seems that the Google Dart does not support mixins (no method bodies in interfaces, no multiple inheritance, no Ruby-like modules). Am I right about this, or is there another way to have mixin-like functionality in Dart?


Solution

  • I'm happy to report that the answer is now Yes!

    A mixin is really just the delta between a subclass and a superclass. You can then "mix in" that delta to another class.

    For example, consider this abstract class:

     abstract class Persistence {  
      void save(String filename) {  
       print('saving the object as ${toJson()}');  
      }  
    
      void load(String filename) {  
       print('loading from $filename');  
      }  
    
      Object toJson();  
     } 
    

    You can then mix this into other classes, thus avoiding the pollution of the inheritance tree.

     abstract class Warrior extends Object with Persistence {  
      fight(Warrior other) {  
       // ...  
      }  
     }  
    
     class Ninja extends Warrior {  
      Map toJson() {  
       return {'throwing_stars': true};  
      }  
     }  
    
     class Zombie extends Warrior {  
      Map toJson() {  
       return {'eats_brains': true};  
      }  
     } 
    

    Restrictions on mixin definitions include:

    • Must not declare a constructor
    • Superclass is Object
    • Contains no calls to super

    Some additional reading: