Typedef in Dart Programming


In Dart, we make use of Typedef when we want to create an alias for a function type that we can use as type annotations for declaring variables and return types of that function type.

A typedef holds type information when a function type is assigned to a variable.

Syntax

typedef functionName(parameters)

We make use of the above syntax when we want to create a Typedef in Dart.

Now, let's take a look at an example when we want to assign a typedef variable to a function in a program.

typdef varName = functionName

Once we have assigned the functionName to a typedef variable, we can later invoke the original function with the help of the typedef variable name.

Consider the syntax shown below −

varName(parameters)

Example

Now, let's create an example in Dart where we will make use of a typedef variable, assign it different functions and later invoke the typedef variable with the varName.

Consider the example shown below −

 Live Demo

typedef operation(int firstNo , int secondNo);

void add(int num1,int num2){
   print("Sum of num1 + num2 is: ${num1+num2}");
}

void subtract(int num1,int num2){
   print("Subtraction of num1 - num2 is: ${num1-num2}");
}

void main(){
   operation op = add;
   op(10,20);
   op = subtract;
   op(20,10);
}

Output

Sum of num1 + num2 is: 30
Subtraction of num1 - num2 is: 10

Updated on: 24-May-2021

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements