First Look at Dart Mixins

You can use mixins to help inject behavior into your classes without using inheritance. Use a mixin when you have shared functionality that doesn't fit well in a is-a relationship.



Dart supports a basic form of mixins as of the M3 release in early 2013. The language designers expect to expand on mixins' abilities in future versions of the language.

Surprisingly, you've been using the concept of a mixin all along. Dart considers a mixin as the delta between a subclass and its superclass. That is, every time you define an is-a relationship with the extends keyword, you are really defining a delta between the new class and its parent class. In other words, a subclass definition is like a mixin definition.

Given that short description, it should come as no surprise that an abstract class (with a few restrictions) is itself a mixin. Here is an example of a Persistance mixin:

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

Restrictions on mixin definitions include:
  1. Must not declare a constructor
  2. Superclass is Object
  3. Contains no calls to super
You can use the mixin with the with keyword. Here is an example:

 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};  
  }  
 } 

In the above example, both Ninja and Zombie extend from Warrior. This makes sense, they are both warriors, so the is-a relationship applies. All warriors can be persisted and loaded from a database, but this is purely behavior and the statement Warrior is-a Persistence simply doesn't make sense. Inheritance does not apply here, but we can use a mixin to inject the functionality.

 main() {  
  var ninja = new Ninja();  
  ninja.save('warriors.txt');  
    
  var zombie = new Zombie();  
  zombie.save('warriors.txt');  
 }  

A class that uses a mixin is also a member of the mixin's type:


 print(ninja is Persistence); // true!  


Mixins are fairly new to Dart, so they aren't widely deployed. We're curious to see how you use mixins. Let us know on the Dart mailing list, and please file any bugs you may encounter. Thanks!

Popular posts from this blog

The 29 Healthiest Foods on the Planet

Lists and arrays in Dart

Converting Array to List in Scala