开发者

Does Google Dart support mixins?

I've skimmed through the language documentation and it seems that the Google Dart does not support mixins (no me开发者_如何学Pythonthod 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?


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:

  • http://www.dartlang.org/articles/mixins/
  • http://blog.sethladd.com/2013/03/first-look-at-dart-mixins.html


Edit:

The Dart team have now released their proposal for Mixins, the original issue for Mixins was here.

It's not implemented yet, but in the meantime I've released an extensible Mixins library for Dart which includes a port of the popular Underscore.js functional utility library: https://github.com/mythz/DartMixins

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜