loading

Dart Callable Classes

You can call class instances just like a function in Dart. We must implement the call() method in a callable class. Let’s examine the subsequent illustration:

Example

				
					class Student {  
  String call(String name, int age) {  
              return('Student name is $name and Age is $age');  
  
           }  
}  
void main() {  
   Student stu = new Student();  
   var msg = stu('Sharma',18);     // Class instance called like a function.  
   print('Dart Callable class');  
   print(msg);  
}  
				
			

Output

				
					Dart Callable class
Student name is Sharma and Age is 18
				
			

Explanation

The call() function, which has two arguments—a string name and an integer age—and returns a message containing these data, is defined in the code above for the class Student. Next, we generated the Student class object and invoked it akin to a function.

				
					var msg = stu('Sharma',18);       
				
			

Example

				
					class Student {  
  String call(String name, int age) {  
              return('Student name is $name and Age is $age');  
  
           }  
}  
  
class Employee {  
  int call(int empid, int age) {  
              return('Employee id is ${empid} and Age is ${age}');  
  
           }  
}  
  
void main() {  
   Student stu = new Student();  
  
   Employee emp = new Employee();  
  
   var msg = stu('peter',18);  // Class instance called like a function.  
   var msg2 = emp(101,32);   // Class instance called like a function.  
   print('Dart Callable class');  
   print(msg);  
   print(msg2);  
}  
				
			

Output

				
					Dart Callable class
Student name is peter and Age is 18
Employee id is 101 and Age is 32
				
			

Explanation

We defined two callable functions in the  class Student and class Employee in the code above. String empid and int age are the two parameters that the Employee class call() method accepts. Both class instances were invoked as callable functions.

				
					var msg = stu('peter',18);    
var msg2 = emp(101,32);  
				
			
Share this Doc

Dart Callable Classes

Or copy link

Explore Topic