在Dart中,函數是對象,就像字符串和數字是對象一樣。typedef或function-type為函數提供一個類型別名,你可以在聲明字段和返回類型時使用這個名稱。當函數類型被分配給變量時,typedef保留類型信息。
以下代碼不使用typedef:
~~~
class SortedCollection {
Function compare;
SortedCollection(int f(Object a, Object b)) {
compare = f;
}
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
void main() {
SortedCollection coll = SortedCollection(sort);
// All we know is that compare is a function,
// but what type of function?
assert(coll.compare is Function);
}
~~~
Type information is lost when assigning f to compare. The type of f is (Object, Object) → int (where → means returns), yet the type of compare is Function. If we change the code to use explicit names and retain type information, both developers and tools can use that information.
當給compare分配f時類型信息會丟失。f的類型是(Object, Object)->int(int表示返回值類型),當然compare的類型是Function。如果我們更改代碼以使用顯式名稱和保留類型信息,開發人員和工具都可以使用這些信息。
~~~
typedef Compare = int Function(Object a, Object b);
class SortedCollection {
Compare compare;
SortedCollection(this.compare);
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
void main() {
SortedCollection coll = SortedCollection(sort);
assert(coll.compare is Function);
assert(coll.compare is Compare);
}
~~~
>注意:目前,typedefs僅限于函數類型。我們期望這種情況會改變。
>
因為typedef僅僅是別名,所以它們提供了一種檢查任何函數類型的方法。例如:
~~~
typedef Compare<T> = int Function(T a, T b);
int sort(int a, int b) => a - b;
void main() {
assert(sort is Compare<int>); // True!
}
~~~