Callable classes is an interested feature of Dart I found recently. With this feature, Dart allows you to use class instances like functions.
Callable classes specifications
- To create a callable class, we implement call method inside the class.
- You can pass any parameters to the call method, and return any data type you want.
- In one class, you can only have one call method, if you create more than one, the error “The name call is already defined” will be thrown.
Example 1
void main() {
final student = Student();
print(student('Phuc', 'Tran'));
}
class Student {
// Parameters: String, String
// Return: String
String call(String firstName, String lastName) {
return '$firstName $lastName';
}
}
Output
Student full name: Phuc Tran
Example 2
void main() {
final employee = Employee();
print('Age = ${employee(1988)}' );
}
class Employee {
// Parameters: int
// Return: int
int call(int yearOfBirth) {
// Calculate the age of employee
return DateTime.now().year - yearOfBirth;
}
}
Output
Age = 32
Example 3: Error when we try to create multiple call methods
