美文网首页
Dart语言基础之typedef

Dart语言基础之typedef

作者: 星空下奔跑 | 来源:发表于2019-04-11 23:21 被阅读0次

在Dart中,函数是对象,就像字符串,数字是对象。 typedef或函数类型别名为函数类型提供了可以用来声明字段和返回类型的名称。 当函数类型分配给变量时,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);
}

将f分配给比较时,类型信息会丢失。 f的类型是(Object,Object)→int(其中→表示返回),但比较的类型是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);
}

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

相关文章

  • Dart语言基础之typedef

    在Dart中,函数是对象,就像字符串,数字是对象。 typedef或函数类型别名为函数类型提供了可以用来声明字段和...

  • dart入门潜修系列教程

    dart入门潜修基础篇之基本语法和内置类型dart入门潜修基础篇之方法dart入门潜修基础篇之操作符dart入门潜...

  • Flutter系列(2)Dart语言基础

    Flutter的开发语言是Dart语言的,这篇文章就说说Dart语言基础 一、Dart 初体验 在flutter项...

  • 函数接口防抖

    copy to dartpad test; ‘’‘dart typedef HttpRequestMethod =...

  • Flutter-Dart基础语法入门

    Dart语法基础 Dart语言简介 Dart是Google推出的一门编程语言,最初是希望取代Javascript运...

  • Dart语言基础,Dart 基础

    Dart 的main方法有两种声明方式 注释 变量的声明 、命名规则、数组类型 Dart是一个强大的脚本类语言,可...

  • Dart基础语法

    Dart基础语法 基本数据类型 Dart 属于强类型语言(在Dart2.0之前,Dart是一门弱类型语言。2.0以...

  • Flutter之Dart语言基础

    Dart语言的诞生 2011年10月,Google 发布了一种新的编程语言 Dart,谷歌希望利用这款语言,帮助程...

  • Dart语言基础之反射

  • Dart语言基础之异常

    原文:https://www.dartlang.org/guides/language/language-tour...

网友评论

      本文标题:Dart语言基础之typedef

      本文链接:https://www.haomeiwen.com/subject/anmfwqtx.html