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:
- new List();
works just fine. Of course, you can write
- new List<String>();
if you want.
- new List();
is just a shorthand for
- 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.
- new List<String>() is List<Object> // true: every string is an object
- 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:
- new List<String>() is List<int> // false
- new List<String>() is List // true
- new List<String>() is List<Dynamic> // same as line above
- 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:
- 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.
Soure:http://www.dartlang.org
No comments:
Post a Comment