What is a typedef in Dart?

后端 未结 5 1604
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 15:34

I have read the description, and I understand that it is a function-type alias.

  • A typedef, or function-type alias, gives a function type a name that you can

5条回答
  •  死守一世寂寞
    2020-12-04 15:50

    Typedef in Dart is used to create a user-defined function (alias) for other application functions,

    Syntax: typedef function_name (parameters);
    

    With the help of a typedef, we can also assign a variable to a function.

    Syntax:typedef variable_name = function_name;
    

    After assigning the variable, if we have to invoke it then we go as:

    Syntax: variable_name(parameters);
    

    Example:

    // Defining alias name
    typedef MainFunction(int a, int b);
    
    functionOne(int a, int b) {
      print("This is FunctionOne");
      print("$a and $b are lucky numbers !!");
    }
    
    functionTwo(int a, int b) {
      print("This is FunctionTwo");
      print("$a + $b is equal to ${a + b}.");
    }
    
    // Main Function
    void main() {
      // use alias
      MainFunction number = functionOne;
    
      number(1, 2);
    
      number = functionTwo;
     // Calling number
      number(3, 4);
    }
    

    Output:

    This is FunctionOne
    1 and 2 are lucky numbers !!
    This is FunctionTwo
    3 + 4 is equal to 7
    

提交回复
热议问题