Dart : Typedef Keyword :
Jeet Bhalu
2 min read
Typedef Keyword :
- In Dart, the typedef is used to generate an alias for function type that we can use it as type annotation for declaring variables and return types of that function type. An alias of function type can be used as type annotation in variable declaration or function return type. A typedef stores the type information when we assigned the function type to a variable.
Declaring a typedef :
- A typedef keyword is used to create an alias for function that will be the same as the actual functions. We can also create a function prototype with a list of parameters. The syntax is given below.
syntax :
typedef function_name(parameters)
Example :
Let's create an alias of MultiOperation(int n1, int n2) that contains two parameters of the integer type.
typedef MultiOperation(int n1, int n2); // function signature
Assigning typedef Variable :
- We can assign any function with the same parameter to the typedef variable. The syntax is given below.
Syntax :
type_def var_name = function_name;
typedef realexam(int one, int two);
real1(int one, int two) {
print('object called with a');
print('object called with b $one and $two');
}
real2(int one, int two) {
print('object called without a');
print('$one + $two');
}
void main() {
realexam obj = real1;
obj(1, 2);
obj = real2;
obj(3, 4);
print(obj);
}
Output :
object called with a
object called with b 1 and 2
object called without a
3 + 4
Closure: (int, int) => dynamic from Function 'real2': static.
Exited.
0
Subscribe to my newsletter
Read articles from Jeet Bhalu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
DevOps Journey#DevopscommunityDart#dart language#dart-for-beginnersdart programming tutorial#dart-keywordsDevopsDeveloperDevops articlesdevelopmentdevOpen SourceObject Oriented ProgrammingProgramming Blogs
Written by
Jeet Bhalu
Jeet Bhalu
i am Jeet Bhalu i am flutter App developer