Skip to main content

Proposal for First-class Types in Dart

Posted by Gilad Bracha

First-class Types in Dart

Currently Dart does not provide any access to types as objects at the base level.  We propose to provide a getter on class Object:

@native Type get type;

which returns a reified representation of the class of an object.  Note that the method type can be overridden in subclasses (for example, to implement a remote proxy that hides its implementation).

The declaration of class Type is

class Type {
 @native String toString();
 String descriptor(){...} // return the simple name of the type

In other words, Type does not add any API to Object, other than the ability to get its name.  One can use toString() to obtain a description of the type (such as its name), one can test types for equality or identity, one can hash them (assuming we move forward on making all objects hashable) and that is all. The main use of these reified types is to serve as keys to the mirror system. Instances of Type are canonicalized.

An identifier that denotes a type in Dart may now be used in an expression, and denotes the corresponding reified type object. Examples:

new Object().type === Object; // evaluates to true
new Mirrors.reflect(Map);
Type c = List; // List<Dynamic>
Type t = new List<int>().type;
Type s = List<String>; // this requires adjustment to the grammar
class G<T> { foo() {
 Type t = T;
 InterfaceMirror m1 = new Mirrors.reflect(t);
 InterfaceMirror m2 = new Mirrors.reflect(T);

The opposite is not the case: one cannot use an expression in contexts where types or classes are specifically required, even if said expression evaluates to a Type object. Hence, the following are illegal:

new List() is c;
// error: assume c is bound to List as above; still, c denotes a variable, not a type

class G<T> {
  T t = new T();
  // error: T is  a type variable bound to some instance of Type, but not class or interface
  static foo() => 42;
  Type gc = G; // G<Dynamic>
  int bar =; // error: gc is bound to G, but denotes a variable not a type

No doubt there will be requests to expand the capabilities of class Type to allow the scenarios shown above.  At this time, the expectation is that mirrors  should be used in such cases; that is, use the reified class as a convenient way to obtain a mirror and use the mirror to obtain the desired functionality, as indicated below:

class G<T> {
  T t = new Mirrors.reflect(T).newInstance([],{});
  static foo() => 42;
  Type gc = G;
  int bar = new Mirrors.reflect(gc).invoke(‘foo’, [], {});

Spec Changes

The above does require some changes to the spec. While the addition of Object.type could be construed as a library issue, the changed status of type names to valid expressions requires some adjustments.

3. Overview

Dart is a class-based, single-inheritance, pure object-oriented programming language. Dart is optionally typed and supports reified generics and interfaces.  The runtime type of every object is represented as an instance of class Type which can be obtained by calling the getter  type declared in class Object, the root of the Dart class hierarchy.

Dart programs can be statically checked. The static checker will report some violations of the type rules, but such violations do not abort compilation or preclude execution.

Dart programs may be executed in one of two modes: production mode or checked mode. In production mode, static type annotations have absolutely no effect on execution.  In checked mode, assignments are dynamically checked, and certain violations of the type system raise exceptions at run time.

The coexistence between optional typing and reification is based on the following:

  • Reified type information reflects the types of objects at runtime and may always be queried by dynamic typechecking constructs (the analogs of instanceOf, casts, typecase etc. in other languages). Reified type information includes class and interface declarations, the the runtime type (aka class) of of an object, and type arguments to constructors.
  • Static type annotations determine the types of variables and function declarations (including methods and constructors).
  • Production mode respects optional typing. Static type annotations do not affect runtime behavior.
  • Checked mode utilizes static type annotations and dynamic type information aggressively yet selectively to provide early error detection during development.

Dart programs are organized in a modular fashion into units called libraries. Libraries are units of encapsulation and may be mutually recursive.

However they are not first class.  To get multiple copies of a library running simultaneously, one needs to spawn an isolate.  

10.29 Identifier Reference

An identifier expression consists of a single identifier; it provides access to an object via an unqualified name.

identifier:       IDENTIFIER


BUILT_IN_IDENTIFIER:      abstract
  | as    | assert
  | Dynamic    | factory    | get    | implements
  | interface    | operator    | set    | static    | typedef    ;

   | '$'
   | '_'

   | DIGIT

   | DIGIT
qualified:      identifier ('.' identifier)?

A built-in identifier is one of the identifiers produced by the production BUILT_IN_IDENTIFIER. It is a compile-time error if a built-in identifier is used as the declared name of a class, interface, type variable or type alias. It is a compile-time error to use a built-in identifier other than   Dynamic as a type annotation. It is a static warning if a built-in identifier is used as the name of a user-defined variable, function or label.

Built-in identifiers are identifiers that are used as keywords in Dart, but are not reserved words in Javascript. To minimize incompatibilities when porting Javascript code to Dart, we do not make these into reserved words. Ergo, a built-in identifier may not be used to name a class or type.  In other words, they are treated as reserved words when used as types. This eliminates many confusing situations without causing compatibility problems.

Evaluation of an identifier expression e of the form id proceeds as follows:
Let d be the innermost declaration in the enclosing lexical scope whose name is id. If no such declaration exists in the lexical scope, let d be the declaration of the inherited member named id if it exists.

  • If d is a class, interface, or type alias T, the value of e is the unique instance of class Type reifying T.
  • If d is a type parameter T, then the value of e is the value of the actual type argument corresponding to T that was  passed to the generative constructor that created the current binding of this.
  • If d is a library variable then:
    • If d is of one of the forms var v = ei; , T var v = ei; , final v = ei; , final T v = ei; , const v = ei; or const T v = ei;  and no value has yet been stored into v then the initializer expression ei is evaluated. If the evaluation succeeded yielding an object o, let r = o, otherwise let r = null. In any case, r is stored into v. The value of e is r.
    • If d is of one of the forms const v = e; or const T v = e; the result of the getter is the value of the compile time constant e. Otherwise
    • e evaluates to the current binding of id.  This case also applies if d is a library function declaration, as these are equivalent to function-valued variable declarations.
  • If d is a local variable or formal parameter then e evaluates to the current binding of id.  This case also applies if d is a local function declaration, as these are equivalent to function-valued variable declarations.

  • If d is a static method, then e evaluates to the function defined by d.
  • If d is the declaration of a static variable or static getter declared in class C, then e is equivalent to the getter invocation
  • If d is the declaration of a top level getter, then e is equivalent to the getter invocation id.
  • Otherwise e is equivalent to the property extraction

Popular posts from this blog

Dart in 2016: The fastest growing programming language at Google, 2nd fastest growing in TIOBE Index

Dart was the fastest growing programming language at Google in 2016 with millions of lines of code written. It also made it to TIOBE Index Top 20 this month (see TIOBE's methodology).

It takes time to build something as ambitious as Dart and, in some ways, Dart is still in its infancy. But we're glad the hard work is starting to pay off.

Many thanks to our amazing community!

We're going to celebrate by ... releasing 1.22 next week (as per our usual 6 week release schedule).

AngularDart is going all Dart

Until now, the multiple language flavors of Angular 2 were written as TypeScript source, and then automatically compiled to both JavaScript and Dart. We're happy to announce that we’re splitting the Angular 2 codebase into two flavors – a Dart version and a TypeScript/JavaScript version – and creating a dedicated AngularDart team.

This is amazing news for Dart developers because:

The framework will feel more like idiomatic Dart.It will make use of Dart features that couldn't work with the TypeScript flavor. It will be faster.
This is equally great news for our TypeScript and JavaScript developers, by the way. Cleaner API, performance gains, easier contributions. Read more on the Angular blog.

Angular 2 for Dart is used by many teams at Google. Most famously by the AdWords team, but many other Google teams build large, mobile-friendly web apps. Some of the top requests from these teams were: make the API feel like Dart, provide a faster edit-refresh cycle, and improve applicat…

The new Google AdSense user interface: built with AngularDart

AdSense is a free, simple way to earn money by placing ads on your website. The team just launched a completely new version of their app for publishers. Read all about it here. We asked Daniel White, the tech lead for the project, some questions because the new UI happens to be built with Dart and Angular2.

AdSense launched way back in 2003. How long is it since the last big redesign?
Last big redesign was called ‘AdSense 3’ and launched about 6 years ago. It was written in Google Web Toolkit (GWT) and the UI has evolved through several iterations - but this is the first ground-up redesign in 6 years. There are a number of long-standing UX issues that we’ve taken the opportunity to solve. A big shout-out to our UX team who’ve been 100% behind this project. We couldn’t have done it without them!

How many software engineers worked on the project?
Purely on the AdSense applications, we have a team of close to 100. Around 25% of them write Dart.

How many lines of code?
We have around 160K LO…