Dart 入门教程(二),函数篇

这是 Dart 入门(中),主要分享函数,Dart 入门教程(上),变量、集合篇。和 JAVA 不一样,Dart 中的函数没有重载方法,这是少见的。还有,在 Dart 中函数可以赋值给变量,这是其他语言中少见的用法。

Dart 入门教程(一),变量、集合篇

Dart 入门教程(二),函数篇

Dart 入门教程(三),运算符篇

Dart 入门教程(四),类的使用

Dart 入门教程(五),同步和异步

位置可选参数

Dart 提供了两种类型的可选参数:位置可选参数和命名可选参数。位置可选参数的特点是必须要按照顺序传入参数。

  void printGreeting(String name, [String? title]) {
    if (title == null) {
      print('Hello, $name!');
    } else {
      print('Hello, $title $name!');
    }
  }

  void main() {
    printGreeting('Alice'); // 输出:Hello, Alice!
    printGreeting('Bob', 'Mr.'); // 输出:Hello, Mr. Bob!
  }

命名可选参数

在调用函数时,可以通过参数名补全参数。相对来说,命名可选参数因为使用灵活,用的更多。

  void printGreeting(String name, {String? title}) {
    if (title == null) {
      print('Hello, $name!');
    } else {
      print('Hello, $title $name!');
    }
  }

  void main() {
    printGreeting('Alice'); // 输出:Hello, Alice!
    printGreeting('Bob', title: 'Mr.'); // 输出:Hello, Mr. Bob!
  }

而且,必传参数、可选参数中,只有可选参数允许有默认值,这点用的非常多,特别是命名可选参数的默认值

  void printGreeting(String name, {String title = 'Friend'}) {
    print('Hello, $title $name!');
  }

  void main() {
    printGreeting('Alice'); // 使用默认值,输出:Hello, Friend Alice!
    printGreeting('Bob', title: 'Mr.'); // 明确指定值,输出:Hello, Mr. Bob!
  }

函数一等公民

和 JAVA 不一样,JAVA 中对象是一等公民,对象作为参数和结果在函数中传递,JAVA 中是不能直接操作函数作为另外一个函数的参数或者结果。但 Dart 中确实可以的。我们可以让一个函数作为另外一个函数的参数或结果

将函数作为参数

  int sum(int a, int b) {
    return a + b;
  }

  int subtract(int a, int b) {
    return a - b;
  }

  int calculate(int a, int b, int Function(int, int) operation) {
    return operation(a, b);
  }

  void main() {
    int a = 5;
    int b = 3;

    print('Sum: ${calculate(a, b, sum)}'); // 输出:Sum: 8
    print('Difference: ${calculate(a, b, subtract)}'); // 输出:Difference: 2
  }

将函数作为返回值

Function selectOperation(String operation) {
  if (operation == 'sum') {
    return (int a, int b) => a + b;
  } else if (operation == 'subtract') {
    return (int a, int b) => a - b;
  } else {
    return (int a, int b) => 0;
  }
}

void main() {
  var sum = selectOperation('sum');
  var subtract = selectOperation('subtract');

  int a = 5;
  int b = 3;

  print('Sum: ${sum(a, b)}'); // 输出:Sum: 8
  print('Difference: ${subtract(a, b)}'); // 输出:Difference: 2
}

匿名函数和箭头函数

匿名函数是没有函数名的函数,开发使用中主要作为参数传递给其他函数。

  void main() {
  	//将匿名函数赋值给 multiply 变量
    var multiply = (int a, int b) {
      return a * b;
    };

    int result = multiply(4, 5);
    print('4 * 5 = $result'); // 输出:4 * 5 = 20
  }

箭头函数使用 => 符号将参数列表和表达式分开。

  void main() {
    var divide = (int a, int b) => a / b;

    double result = divide(10, 2);
    print('10 / 2 = $result'); // 输出:10 / 2 = 5.0
  }

行,函数篇就到这,下篇分享 Dart 的运算符。

Dart 入门教程(一),变量、集合篇

Dart 入门教程(二),函数篇

Dart 入门教程(三),运算符篇

Dart 入门教程(四),类的使用

Dart 入门教程(五),同步和异步

本文由老郭种树原创,转载请注明:https://guozh.net/dart-beginner-tutorial-function/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注