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!
}