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!
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值