Date
May. 19th, 2024
 
2024年 4月 12日

Post: Dart Primer 003 : 函数

Dart Primer 003 : 函数

Published 12:05 May 17, 2018.

Created by @ezra. Categorized in #Programming, and tagged as #Dart.

Source format: Markdown

Table of Content

首先, 如前面所讲, Dart 中函数也是对象的一种。当一个函数没有指定返回值时, 返回 null

函数定义

定义一个函数的格式是:

返回值 函数名(参数类型 参数名1, 参数类型 参数名2, ...) {
  // 函数体
  return 返回值
}

其中类型部分都是可选的:

函数名(参数名1, 参数名2, ...) {
  // 函数体
  return 返回值
}

例如:

String sayHelloTo(String name) {
  return 'Hello $name!';
}
sayHelloTo(name) {
  return 'Hello $name!';
}

对于简单返回一个表达式的函数, 也可以使用 =>exp; 的方式定义, 例如:

sayHelloTo(name) => 'Hello $name!';

匿名函数

类似的, 我们也可以定义匿名函数:

var sayHello = (name) => 'Hello $name!';

函数别名

通过 typedef 关键字我们可以函数别名:

typedef int NumberMagic(int a, int b); // 定义函数别名

int Subtract(int a, int b) => a - b; // 定义普通函数

void main() {
  print(Substract is Function);
  print(Substract is NumberMagic);
}

函数闭包

Function makeSubstract(num n) {
  return (num i) => n - i; // 返回一个函数
}

void main() {
  var x = makeSubstract(5); // 5 对应了前面的 num n
  print(x(2)); // 2 对应了前面的 num i
}

可选参数

对于可选参数的声明有两种方式:

  • 通过大括号 ({}) 包含, 其中可以声明 0 或多个可选参数, 这种方式不关心顺序, 因此调用时需要指明参数名, 未赋值的可选参数将为 null
  • 通过中括号 ([]) 包含, 其中可以声明 0 或多个可选参数, 这种方式会按顺序依次复制参数, 因此调用时可以不指明参数名, 未赋值的可选参数将为 null

例如:

FunX(a, {b, c:3, d:4, e}) {
  print('$a $b $c $d $e');
}

FunY(a, [b, c=3, d=4, e]) {
  print('$a $b $c $d $e');
}

void main() {
  FunX(1, b:3, d:5);
  FunY(1, 3, 5);
}
Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF