Dart (3) - method definition, arrow function, function call to each other, anonymous, self-executing method and closure

Dart (1) - variables, constants, basic types, operators, conditional judgments and type conversions

Dart (2) - Common properties and methods of loop expressions, List, Set and Map

method definition


dart自定义方法的基本格式:

返回类型  方法名称(参数1,参数2,...){
  方法体
  return 返回值 / 或无返回值;
}

A few examples of defining methods:

void printInfo(){
  print('我是一个自定义方法');
}

int getNum(){
  var count = 123;
  return count;
}

String printUserInfo(){

  return 'this is str';
}

List getList(){

  return ['111','2222','333'];
}

Dart does not have keywords such as public , and so on, and  the lower horizontal directly represents it  .private_private

method scope

void main(){

void outFun(){
    innerFun(){

        print('aaa');
    }
    innerFun();
}

// innerFun();  错误写法 

    outFun();  //调用方法
}

method parameter

General definition:

String getUserInfo(String username, int age) {
  //形参
  return "姓名:$username -> 年龄:$age";
}

print(printUserInfo('小明', 23)); //实参

In Dart, you can define a method with optional parameters. Optional parameters need to specify the type default value:

void main() {
  String printUserInfo(String username, [int age = 0]) { //age格式表示可选
    //形参
    if (age != 0) {
      return "姓名:$username -> 年龄:$age";
    }
    return "姓名:$username -> 年龄不详";
  }

  print(printUserInfo('小明', 28)); //实参
  //可选就可以不传了
  print(printUserInfo('李四'));
}

Define a method with default parameters:

String getUserInfo(String username,[String sex='男',int age=0]){  //形参
  if(age!=0){
    return "姓名:$username -> 性别:$sex -> 年龄:$age";
  }
  return "姓名:$username -> 性别:$sex -> 年龄不详";
}
print(getUserInfo('张三'));
print(getUserInfo('李四','男'));
print(getUserInfo('李梅梅','女',25));

To define a method of named parameters, defining a named parameter requires specifying a type default value:

The advantage of named parameters is that they can be used without assigning them in order, see the following code:

String getUserInfo(String username, {int age = 0, String sex = '男'}) {//形参
  if (age != 0) {
    return "姓名:$username -> 性别:$sex -> 年龄:$age";
  }
  return "姓名:$username -> 性别:$sex -> 年龄保密";
}
print(getUserInfo('张三',sex: '男',age: 20));

Define a method that takes a method as a parameter:

In fact, methods can be used as parameters, which Kotlinis the same as:

//方法1 随便打印一下
fun1() {
  print('fun1');
}

//方法2 参数是一个方法
fun2(fun) {
  fun();
}

//调用fun2这个方法 把fun1这个方法当做参数传入
fun2(fun1());

Arrow function and function call to each other

arrow function

In the previous study, we know that we can use forEachto traverse List, the general format is as follows:

List list = ['a', 'b', 'c'];
list.forEach((value) {
  print(value);
});

Arrow functions can be shortened to this format:

list.forEach((value) => print(value));

The arrow behind the arrow points to the return value of the method. It should be noted here that:

Only one statement can be written in an arrow function, and there is no semicolon (;) after the statement

mapThe arrow method can also be used to simplify the previous conversion example:

List list = [1, 3, 6, 8, 9];
var newList = list.map((value) {
  if (value > 3) {
    return value * 2;
  }
  return value;
});

Here is to modify Listthe data inside, multiply the values ​​greater than 3 in the array by 2. That can be simplified with arrow functions and can be written as:

var newList = list.map((value) => value > 3 ? value*2 : value);

One sentence of code completion, very interesting.

Mutual call of functions

  // 定义一个方法来判断一个数是否是偶数  
  bool isEvenNumber(int n) {
    if (n % 2 == 0) {
      return true;
    }
    return false;
  }
  // 定义一个方法打印1-n以内的所有偶数
  prinEvenNumber(int n) {
    for (var i = 1; i <= n; i++) {
      if (isEvenNumber(i)) {
        print(i);
      }
    }
  }
  prinEvenNumber(10);

Anonymous methods, self-executing methods, and recursion of methods

anonymous method

var printNum = (){
  print(12);
};
printNum();

It is obvious here Kotlinthat the features are basically the same as in . Anonymous method with parameters:

var printNum = (int n) {
  print(n + 2);
};

printNum(3);

self-executing method

As the name implies, the self-executing method does not need to be called and will be executed automatically, because the definition and invocation of the self-executing function are integrated. When we create an anonymous function and execute it, since its internal variables cannot be referenced from the outside, it will be released soon after execution, and this approach will not pollute the global object. See the following code:

((int n) {
    print("这是一个自执行方法 + $n");
  })(666);
}

method recursion

The recursion of the method is nothing more than continuing to call itself within the method under the condition that the condition is satisfied, see the following code:

var sum = 0;
void fn(int n) {
  sum += n;
  if (n == 0) {
    return;
  }
  fn(n - 1);
}
fn(100);
print(sum);

The implementation is to add 1 to 100.

Closure

Closure is a front-end concept. In the early stage of client development, Javait can be said that it does not support closure, or an incomplete closure, Kotlinbut it can support the operation of closure.

Closure means function nested function, the inner function will call the variables or parameters of the outer function, and the variables or parameters will not be reclaimed by the system (the memory will not be released) . So the two problems that closures solve are:

  • variable resident memory
  • Variables do not pollute the global

The general way of writing a closure is:

  • Functions nest functions and return the functions inside, thus forming a closure .

Closure writing:

Function func() {
  var a = 1; /*不会污染全局   常驻内存*/
  return () {
    a++;
    print(a);
  };
}

After returning the anonymous method here, the value of a can be resident in memory:

var mFun = func();
mFun();
mFun();
mFun();

Print: 2, 3, 4.

Guess you like

Origin juejin.im/post/7116205745367941150