Dart – Callable classes

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

  1. To create a callable class, we implement call method inside the class.
  2. You can pass any parameters to the call method, and return any data type you want.
  3. 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 method

Tagged : / /
5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x