Search code examples
dartprimitive-types

Dart abstract primitives implementation


I was looking around the implementation of basic dart types (double, int, String etc..), I found that many of these classes are abstract. I'm wondering if these classes are abstract then which class implements them? How is an object assigned to a specific type when these classes cannot even be instantiated? For example,

double being an abstract class I cannot instantiate it like

var d = double();

But then how does

var d = 2.5;
print(d is double);

prints true? How does dart knows that d is an object of double?


Solution

  • The Dart platform libraries are split into the public, shared code that you are looking at, and internal, platform-dependent code ("patch files") which provide implementations for functions that are declared external, and which also supply the other internal machinery that the platform depends on (and then there is also the native guts of the run-time system).

    Those platform specific files contain declarations of classes which implement types like int and String. The specification says that you cannot subclass int and String, but the runtime system does so anyway. Your "primitive" objects are instances of those hidden sub-classes of the abstract interface.

    The run-time system can (and does) then optimize the representation of some of those classes even more. For example, the VM has a subtype of int called Smi ("small integer") which stores the value in the pointer instead of allocating an object in the heap, and the web platforms implement int as a plain JavaScript number. They have to treat those values specially when you call methods on them, because they are not structured the same as other objects. But that's an optimization, you can think of the values as just being implemented by internal hidden classes.