Dart by Example: Mixins

  1. import 'dart:math';
  2. class Position {
  3. int x;
  4. int y;
  5. double distanceTo(Position other) {
  6. var dx = other.x - x;
  7. var dy = other.y - y;
  8. return sqrt(dx * dx + dy * dy);
  9. }
  10. }
  11. class Square {
  12. int width;
  13. int height;
  14. int get area => width * height;
  15. }
  16. // Classes can be mixed in using 'with'
  17. class SquareView extends Square with Position {}
  18. main() {
  19. var origin = new Position()
  20. ..x = 0
  21. ..y = 0;
  22. var square = new SquareView()
  23. ..x = 5
  24. ..y = 5
  25. ..width = 10
  26. ..height = 10;
  27. print(square.distanceTo(origin));
  28. print(square.area);
  29. }
  30.  
  1. $ dart mixins.dart
  2. 7.0710678118654755
  3. 100

by @jryanio | source | license