Thursday, 23 February 2012

Google DART Generics


Generics

Dart supports reified generics. That is, objects of generic type carry their type arguments with them at run time. Passing type arguments to a constructor of a generic type is a runtime operation. How does this square with the claim that types are optional?
Well, if you don’t want to ever think about types, generics won’t force you to. You can create instances of generic classes without providing type parameters. For example:
  1. new List();
works just fine. Of course, you can write
  1. new List<String>();
if you want.
  1. new List();
is just a shorthand for
  1. new List<Dynamic>();
In constructors, type parameters play a runtime role. They are actually passed at run time, so that you can use them when you do dynamic type tests.
  1. new List<String>() is List<Object> // true: every string is an object
  2. new List<Object>() is List<String> // false: not all objects are strings
Generics in Dart conform to programmer intuition. Here are some more interesting cases:
  1. new List<String>() is List<int> // false
  2. new List<String>() is List // true
  3. new List<String>() is List<Dynamic> // same as line above
  4. new List() is List<Dynamic> // true, these are exactly the same
In contrast, type annotations (for example, types added to the declarations of variables, or as return types of functions and methods) play no runtime role and have no effect on program semantics. One last case worth studying:
  1. new List() is List<String> // true as well!
You may be writing your program without types, but you will frequently be passing data into typed libraries. To prevent types getting in your way, generic types without type parameters are considered substitutable (subtypes of) for any other version of that generic.

No comments:

Post a Comment