Dart Callable Classes

 

Dart Callable Classes

Dart provides the facility to call class instances like a function. To make callable class, we need to implement a call() method in it. Let's understand the following example -

Example - 1

  1. class Student {  
  2.   String call(String name, int age) {  
  3.               return('Student name is $name and Age is $age');  
  4.   
  5.            }  
  6. }  
  7. void main() {  
  8.    Student stu = new Student();  
  9.    var msg = stu('Sharma',18);     // Class instance called like a function.  
  10.    print('Dart Callable class');  
  11.    print(msg);  
  12. }  

Output

Dart Callable class
Student name is Sharma and Age is 18

Explanation:

In the above code, We defined a call() function in the class Student that takes two arguments String name, integer age and return a message with this information. Then, we have created the object of class Student and called it like a function.

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

Let's have a look at another example -

Example - 2 Multiple callable class

  1. class Student {  
  2.   String call(String name, int age) {  
  3.               return('Student name is $name and Age is $age');  
  4.   
  5.            }  
  6. }  
  7.   
  8. class Employee {  
  9.   int call(int empid, int age) {  
  10.               return('Employee id is ${empid} and Age is ${age}');  
  11.   
  12.            }  
  13. }  
  14.   
  15. void main() {  
  16.    Student stu = new Student();  
  17.   
  18.    Employee emp = new Employee();  
  19.   
  20.    var msg = stu('peter',18);  // Class instance called like a function.  
  21.    var msg2 = emp(101,32);   // Class instance called like a function.  
  22.    print('Dart Callable class');  
  23.    print(msg);  
  24.    print(msg2);  
  25. }  

Output

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

Explanation:

In the above code, we defined two callable functions in class Student and class Employee. The Employee class call() function accepts two parameters as String empid and int age. We called instances of both classes as callable functions.

  1. var msg = stu('peter',18);    
  2. var msg2 = emp(101,32);  

Comments