Dart 語言簡易教程(三)

Dart 語言簡易教程(一): http://www.lxweimin.com/p/8a62b1a2fd75
Dart 語言簡易教程(二): http://www.lxweimin.com/p/b2153a32dd8b

Dart 語言簡易教程(三)

函數(shù)(Functions)

Dart 是一個(gè)面向?qū)ο蟮恼Z言,所以即使是函數(shù)也是對象,函數(shù)屬于Function對象。
可以通過函數(shù)來指定變量或者像其它的函數(shù)傳遞參數(shù)。

函數(shù)實(shí)現(xiàn)的例子:

bool isNoble(int atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}

可以去掉形式參數(shù)數(shù)據(jù)類型和返回值的數(shù)據(jù)類型。
下面的例子演示了這些:

isNoble(atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}

如果函數(shù)只有單個(gè)語句,可以采用簡略的形式:

bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;

The => expr; syntax is a shorthand for { return expr;}.

函數(shù)可以有兩中類型的參數(shù):

  • 必須的
    必須的參數(shù)放在參數(shù)列表的前面。
  • 可選的
    可選的參數(shù)跟在必須的參數(shù)后面。

可選的參數(shù)

可以通過名字或位置個(gè)函數(shù)指定可選參數(shù)。

可選的名字參數(shù)

在調(diào)用函數(shù)時(shí),可以指定參數(shù)的名字及相應(yīng)的取值,采用paramName: value的格式。
例如函數(shù)定義:

/// Sets the [bold] and [hidden] flags to the values
/// you specify.
enableFlags({bool bold, bool hidden}) {
  // ...
}

函數(shù)調(diào)用:

enableFlags(bold: true, hidden: false);

可選的位置參數(shù)

將參數(shù)使用[] 括起來,用來表明是可選位置參數(shù)。
例如下面的例子,函數(shù)定義:

String say(String from, String msg, [String device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}

調(diào)用函數(shù)不包含第三個(gè)參數(shù):

assert(say('Bob', 'Howdy') == 'Bob says Howdy');

調(diào)用函數(shù)包含第三個(gè)參數(shù):

assert(say('Bob', 'Howdy', 'smoke signal') ==
    'Bob says Howdy with a smoke signal');

參數(shù)默認(rèn)值

可以定義包含默認(rèn)位置參數(shù)或默認(rèn)名字參數(shù)的函數(shù)。參數(shù)的默認(rèn)值必須是編譯時(shí)的靜態(tài)值。
假如定義函數(shù)時(shí),沒有指定默認(rèn)的參數(shù)值,則參數(shù)值默認(rèn)為null

  • 使用冒號(:)來設(shè)置默認(rèn)名字參數(shù)。

// Sets the [bold] and [hidden] flags to the values you
// specify, defaulting to false.
enableFlags({bool bold: false, bool hidden: false}) {
// ...
}
// bold will be true; hidden will be false.
enableFlags(bold: true);

- 使用等號(`= `)來設(shè)置默位置字參數(shù)。
```Dart
String say(String from, String msg,
    [String device = 'carrier pigeon', String mood]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  if (mood != null) {
    result = '$result (in a $mood mood)';
  }
  return result;
}
assert(say('Bob', 'Howdy') ==
    'Bob says Howdy with a carrier pigeon');

也可以將listsmaps類型作為默認(rèn)值。
如下面的例子:

doStuff({List<int> list: const[1, 2, 3],
         Map<String, String> gifts: const{'first':  'paper',
                                          'second': 'cotton',
                                          'third':  'leather'}}) {
  print('list:  $list');
  print('gifts: $gifts');
}

main() {
  // Use the default values for both parameters.
  doStuff();

  // Use the default values for the "gifts" parameter.
  doStuff(list:[4,5,6]);
  
  // Don't use the default values for either parameter.
  doStuff(list: null, gifts: null);
}

對應(yīng)輸出結(jié)果是:

list:  [1, 2, 3]
gifts: {first: paper, second: cotton, third: leather}
list:  [4, 5, 6]
gifts: {first: paper, second: cotton, third: leather}
list:  null
gifts: null

main() 函數(shù)

所以的APP 都必須有一個(gè)mian()函數(shù),作為APP 的應(yīng)用接入點(diǎn)。
main()函數(shù)返回void 類型,并且包含可選的List< String > 類型的參數(shù)。

main()函數(shù)不包含參數(shù)的例子:

void main() {
  querySelector("#sample_text_id")
    ..text = "Click me!"
    ..onClick.listen(reverseText);
}

main()函數(shù)包含參數(shù)的例子:

// Run the app like this: dart args.dart 1 test
void main(List<String> arguments) {
  print(arguments);

  assert(arguments.length == 2);
  assert(int.parse(arguments[0]) == 1);
  assert(arguments[1] == 'test');
}

傳遞函數(shù)給函數(shù)

  • 可以將一個(gè)函數(shù)作為一個(gè)參數(shù)傳遞給另一個(gè)函數(shù)。例如:

    printElement(element) {
      print(element);
    }
    
    var list = [1, 2, 3];
    
    // Pass printElement as a parameter.
    list.forEach(printElement);
    
  • 也可以將函數(shù)賦值給一個(gè)變量。例如:

    var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!';
    assert(loudify('hello') == '!!! HELLO !!!');
    

變量作用范圍

嵌套的函數(shù)中可以訪問包含他的函數(shù)中定義的變量。例如:

var topLevel = true;

main() {
  var insideMain = true;

  myFunction() {
    var insideFunction = true;

    nestedFunction() {
      var insideNestedFunction = true;

      assert(topLevel);
      assert(insideMain);
      assert(insideFunction);
      assert(insideNestedFunction);
    }
  }
}

變量閉合

函數(shù)可以返回一個(gè)函數(shù)。例如:

/// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(num addBy) {
  return (num i) => addBy + i;
}

main() {
  // Create a function that adds 2.
  var add2 = makeAdder(2);

  // Create a function that adds 4.
  var add4 = makeAdder(4);

  assert(add2(3) == 5);
  assert(add4(3) == 7);
}

函數(shù)返回值

所以的函數(shù)都會(huì)有返回值。
如果沒有指定函數(shù)返回值,則默認(rèn)的返回值是null
沒有返回值的函數(shù),系統(tǒng)會(huì)在最后添加隱式的return 語句。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容