别名

Last updated: ... / Reads: 35 Edit

类型别名(通常称为 typedef,因为它是用关键字 typedef 声明的)是一种引用类型的简洁方式。下面是声明和使用名为 IntList 的类型别名的示例:

typedef IntList = List<int>;
IntList il = [1, 2, 3];

类型别名可以有类型参数:

typedef ListMapper<X> = Map<X, List<X>>;
Map<String, List<String>> m1 = {}; // Verbose.
ListMapper<String> m2 = {}; // Same thing but shorter and clearer.

版本提示:在 2.13 之前,typedef 仅限于函数类型。使用新的 typedef 需要至少 2.13 的语言版本。

在大多数情况下,我们建议使用内联函数类型而不是函数的 typedef。然而,函数 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!
}

Comments

Make a comment