Monday, 10 October 2011

Optional types

Dart provides, at the programmer’s option, a mixture of static and dynamic checking. When experimenting, the programmer can write untyped code for simple prototyping. As the application becomes larger and more stable, types can be added to aid debugging and impose structure where desired.
For example, here is a sample of untyped code in Dart that creates a new Point class that has parameters x and y and two methods: scale() and distance().
 
class Point {
  var x, y;
  Point(this.x, this.y);
  scale(factor) => new Point(x*factor, y*factor);
  distance() => Math.sqrt(x*x + y*y);
}

main() {
  var a = new Point(2,3).scale(10);
  print(a.distance());
}

Here is what this code looks like with types added that ensure that x, y, and factor are of type num, and that a Point contains two values of type num:

class Point {
  num x, y;
  Point(num this.x, num this.y);
  Point scale(num factor) => new Point(x*factor, y*factor);
  num distance() => Math.sqrt(x*x + y*y);
}

void main() {
  Point a = new Point(2,3).scale(10);
  print(a.distance());
}

No comments:

Post a Comment