若是你看API文档中的数组篇,你会发现类型通常写成List
泛型是类型安全的(意思是你必须指定数据的类型),可是它的写法比硬编码指定类型高效的多:java
若是你想让数组只有String值,定义为List
var names = List<String>(); names.addAll(['Seth', 'Kathy', 'Lars']); names.add(42); // Error
另外一个使用泛型是缘由是为了减小重复代码。泛型让你经过一个单一类能够适配多种类型的数据操做,同时能够进行静态代码检查(好比,类型安全检查)。数组
abstract class ObjectCache { Object getByKey(String key); void setByKey(String key, Object value); }
上面代码是对Object类型操做,在没用泛型的状况下,你想对String类型操做,就得从新定义一个类安全
abstract class StringCache { String getByKey(String key); void setByKey(String key, String value); }
后面,你若是相对num类型操做,还得从新定义一个类。编码
而泛型就能够解决上面的问题,它经过对类型参数化,实现一个类针对多种数据类型操做的适配。翻译
abstract class Cache<T> { T getByKey(String key); void setByKey(String key, T value); }
List和map的字面量rest
List和map的字面量方式能够用指定类型参数。code
var names = <String>['Seth', 'Kathy', 'Lars']; var pages = <String, String>{ 'index.html': 'Homepage', 'robots.txt': 'Hints for web robots', 'humans.txt': 'We are people, not machines' };
var names = List<String>(); names.addAll(['Seth', 'Kathy', 'Lars']); var nameSet = Set<String>.from(names);
下面是map的泛型构造写法:htm
var views = Map<int, View>();
Dart的泛型类型是在运行时绑定的,这样,在运行时,能够知道List内具体类型。
var names = List<String>(); names.addAll(['Seth', 'Kathy', 'Lars']); print(names is List<String>); // true
注意:java中,泛型是采用擦除的方式,它在运行时,其实对象都是Object类型或者泛型的约束父类。
当泛型时,但愿限制参数的类型范围,能够用extends关键字约束。
class Foo<T extends SomeBaseClass> { // Implementation goes here... String toString() => "Instance of 'Foo<$T>'"; } class Extender extends SomeBaseClass {...}
添加约束后,只要是指定的父类或者其子类均可以做为泛型参数。
var someBaseClassFoo = Foo<SomeBaseClass>(); var extenderFoo = Foo<Extender>();
也能够不指定泛型参数。
var foo = Foo(); print(foo); // Instance of 'Foo<SomeBaseClass>'
不能够用限定范围的泛型参数,这样静态代码检查器将提示错误。
var foo = Foo<Object>();
Initially, Dart’s generic support was limited to classes. A newer syntax, called generic methods, allows type arguments on methods and functions:
T first<T>(List<T> ts) { // Do some initial work or error checking, then... T tmp = ts[0]; // Do some additional checking or processing... return tmp; }
下面是容许使用泛型方法的场景:
In the function’s return type (T).
In the type of an argument (List