Friday, 7 June 2013

Dart numeric types

As previously mentioned, I started to take a look at the Dart programming language.

When I first started to play around with Dart, I fairly quickly came across a strange but seemingly trivial number type conversion problem. It can be expressed easily by this code:

  int a = 60;   int b = 5;   int c = a/b;
This produces an error at runtime:
  type 'double' is not a subtype of type 'int' of 'c'.
After some investigation it appears to be the "fault" of Javascript, in which there are only floating point numbers and not integers. This presents a problem for Dart as all code is supposed to be exportable to Javascript.

But still, might you not expect any language to cope with simple integer arithmetic like this? It's as though division simply cannot be done on integers! The solution is to either use the (a/b).toInt() function to force conversion to integer, or to change the variable types from 'int' to 'num'.