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


  1. Why isn't Type the same as new Mirrors.reflect(Type)? Like, what are we avoiding here?


Post a Comment

Popular posts from this blog

Const, Static, Final, Oh my!

Posted by Seth Ladd

(This is an "oldie but a goodie" post originally written by Bob Nystrom. It is being posted here as the explanations still ring true.)

Bob writes:

"static", "final", and "const" mean entirely distinct things in Dart:

"static" means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies *members*.

"final" means single-assignment: a final variable or field *must* have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies *variables*.

"const" has a meaning that's a bit more complex and subtle in Dart. const modifies *values*. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determ…

The new AdWords UI uses Dart — we asked why

Google just announced a re-designed AdWords experience. In case you’re not familiar with AdWords: businesses use it to advertise on and partner websites. Advertising makes up majority of Google’s revenue, so when Google decides to completely redo the customer-facing front end to it, it’s a big deal. The Dart team is proud to say that this new front end is built with Dart and Angular 2. Whenever you asked us whether Google is ‘even using Dart for anything,’ this is what we had in mind but couldn’t say aloud. Until now. We asked Joshy Joseph, the primary technical lead on the project, some questions. Joshy is focusing on things like infrastructure, application latency and development velocity, so he’s the right person to ask about Dart.Q: What exactly did we launch on Monday?It’s a complete redesign of the AdWords customer experience that is rolling out slowly as a test to a small initial set of advertisers. The most noticeable thing is probably the Material Design look and f…

Dart 1.12 Released, with Null-Aware Operators and more

Dart 1.12.0 is now released! It contains the new null-aware operators language feature, and enhancements to pub, Observatory, dartdoc, and much more.

Null-aware operators

The new null-aware operators help you reduce the amount of code required to work with references that are potentially null. This feature is a collection of syntactic sugar for traversing (potentially null) object calls, conditionally setting a variable, and evaluating two (potentially null) expressions.

Click or tap the red Run button below to see them in action.


  if null operator. `expr1 ?? expr2` evaluates to `expr1` if not `null`, otherwise `expr2`.


  null-aware assignment. `v ??= expr` causes `v` to be assigned `expr` only if `v` is `null`.


  null-aware access. `x?.p` evaluates to `x.p` if `x` is not `null`, otherwise evaluates to `null`.


  null-aware method invocation. `x?.m()` invokes `m` only if `x` is not `null`.

Learn more about Dart's null-aware operators in our Language Tour.

.packages fi…