Dart 08 函數別名 Typedef

Typedefs

在 Dart 中,函數也是對象,就像字符和數字對象一樣。

使用 typedef 爲函數起一個別名

  • 別名可以用來聲明字段及返回值類型。
  • 當函數類型分配給變量時,typedef會保留類型信息。
  • 請考慮以下代碼,代碼中未使用 typedef :
main() {
  TestFun testFun = TestFun(fun);
  print(testFun.f is Function);
//  print(testFun.f is fun);// 這句話將產生異常
}

// 定義一個返回值爲int 的函數 fun
int fun(Object a, Object b) => 0;

class TestFun {
  var f;
  TestFun(int fun(Object a, Object b)) {
    f = fun;
  }
}
  • 當把函數fun 在作爲參數傳遞給f的時候 fun 的類型丟失了

  • fun原本的類型應該是int fun(Object a, Object b) 但是我們並不能通過testFun.f is int fun(Object a, Object b)去判斷, 只知道 testFun.f 是一個Funcation

  • 但是通過typedef 別名 我們可以記錄函數類型信息 這樣開發者和工具都可以使用這些信息:

main() {
  TestFun testFun = TestFun(fun);
  // 通過func判斷
  print(testFun.f is func);
  print(testFun.f is func1);
}

// 定義一個返回值爲int 的函數 fun
int fun(Object a, Object b) => 0;
// 給函數傳遞a b 返回int 的函數定義別名 func
// 方式一 別名 後面只能是 Funcation
typedef func = int Function(Object a, Object b);
// 方式二 函數名就是別名
typedef int func1(Object a, Object b);

class TestFun {
  var f;
  TestFun(int fun(Object a, Object b)) {
    f = fun;
  }
}
// 輸出
//true
//true

提示: 目前,typedefs 只能使用在函數類型上, 我們希望將來這種情況有所改變。

由於 typedefs 只是別名, 他們還提供了一種方式來判斷任意函數的類型。例如:

typedef Compare<T> = int Function(T a, T b);
typedef int Compare1<T>(T a, T b);
int sort(int a, int b) => a - b;

void main() {
    assert(sort is Compare<int>); // True!
  assert(sort is Compare1<int>); // True!
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章