In this tutorial you will learn about the Dart Typedef and its application with practical example.
Dart Typedef
In Dart, typedef is used to create an alias for function type that you can use as type annotations for declaring variables and return types of that function type. After creating an alias of function type; we can use it as type annotations in variable declaration or in function return type. A typedef holds type information when a function type is assigned to a variable.
Defining a typedef
A typedef keyword can be used to create an alias for function prototype that will comparable with the actual functions. A function prototype specifies function’s parameters (including their types).
Syntax:-
1 |
typedef function_name(parameters) |
Example:-
Let’s create an alias ManyOperation for a function signature that will take two input parameters of the type integer.
1 |
typedef ManyOperation(int num1, int num2); //function signature |
Assigning typedef Variable
A typedef variable can be assigned any function having the same signature as typedef declaration.
Syntax:-
1 |
type_def var_name = function_name |
Example:-
Now, lets define some functions with the same function signature as that of the ManyOperation typedef.
1 2 3 4 5 6 |
Add(int num1,int num2){ print("Sum of Given No. Is: ${num1+num2}"); } Subtract(int num1,int num2){ print("Subtraction Of Given No. Is: ${num1-num2}"); } |
Invoking Function with typedef
Now, the typedef variable can be used to invoke functions with same function signature.
Syntax:-
1 |
var_name(parameters) |
Example:-
1 2 3 4 5 6 7 |
ManyOperation oper ; //can point to any method of same signature oper = Add; oper(10,20); oper = Subtract; oper(30,20); |
The oper variable can be used to refer any method which takes two integer parameters. The typedefs can switch function references in runtime.
Complete Program In Action
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
typedef ManyOperation(int firstNo , int secondNo); //function signature Add(int num1,int num2){ print("Sum of Given No. Is: ${num1+num2}"); } Subtract(int num1,int num2){ print("Subtraction Of Given No. Is: ${num1-num2}"); } void main(){ ManyOperation oper = Add; print("W3Adda - Dart typedef Example"); oper(10,20); oper = Subtract; oper(20,10); } |
Output:-
Typedefs as Parameter
Lets add one more method to the above program Calculator(int n1,int n2, ManyOperation oper) which accepts two integer numbers (n1 and n2) and one typedef ManyOperation oper as its parameter.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
typedef ManyOperation(int firstNo , int secondNo); //function signature Add(int num1,int num2){ print("Sum of Given No. Is: ${num1+num2}"); } Subtract(int num1,int num2){ print("Subtraction Of Given No. Is: ${num1-num2}"); } Calculator(int a,int b ,ManyOperation oper){ print("Inside calculator"); oper(a,b); } main(){ print("W3Adda - Dart typedef as function parameter"); Calculator(10,20,Add); Calculator(20,10,Subtract); } |
Output:-