Typedef in Dart

Typedef in Dart is used to create a user-defined identity (alias) for a function, and we can use that identity in place of the function in the program code. When we use typedef we can define the parameters of the function.

Syntax: typedef function_name ( parameters );

With the help of 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 );

By this we will be able to use a single function in different ways:

Example 1:  Using typedef in Dart.



Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

// Dart program to show the usage of typedef
 
// Defining alias name
typedef GeeksForGeeks(int a, int b);
 
// Defining Geek1 function
Geek1(int a, int b) {
  print("This is Geek1");
  print("$a and $b are lucky geek numbers !!");
}
 
// Defining Geek2 function
Geek2(int a, int b) {
  print("This is Geek2");
  print("$a + $b is equal to ${a + b}.");
}
 
// Main Function
void main()
{
  // Using alias name to define
  // number with Geek1 function
    GeeksForGeeks number = Geek1;
  // Calling number
  number(1,2);
   
  // Redefining number
  // with Geek2 function
  number = Geek2;
  // Calling number
  number(3,4);
}

chevron_right


Output:

This is Geek1
1 and 2 are lucky geek numbers !!
This is Geek2
3 + 4 is equal to 7.

Note: Apart from this, typedef can also act as parameters of a function.

Example 2: Using typedef as a parameter of a function.

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

// Dart program to show the usage of typedef
 
// Defining alias name
typedef GeeksForGeeks(int a, int b);
 
// Defining Geek1 function
Geek1(int a, int b) {
  print("This is Geek1");
  print("$a and $b are lucky geek numbers !!");
}
 
// Defining a function with a typedef variable
number(int a, int b, GeeksForGeeks geek) {
  print("Welcome to GeeksForGeeks");
  geek(a, b);
}
 
// Main Function
void main()
{
  // Calling number function
  number(21,23, Geek1);
}

chevron_right


Output:

Welcome to GeeksForGeeks
This is Geek1
21 and 23 are lucky geek numbers !!



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : addamkoroma

Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.