What is a callable class in Dart programming language

Dart callable class :

Callable class is a way in dart to change one dart class that makes its instances callable like a function. The only change requires is to implement one new function called call in that class. This function can take different parameters and it can return values like any other normal function.

Example of callable :

Let’s take a look at the below example :

class FindAverage {
  num call(num first, num second) => (first + second) / 2;

main(List<string> args) {
  var avg = FindAverage();

  print(avg(2, 4));
  print(avg(2.8, 4.2));

Here, FindAverage class has call method. This method takes two numbers and returns the average. In the main method, we are creating one instance of this class : avg. Using that instance, we are calling the callable class directly without a function call.

Dart example callable class

Multiple call function in same class :

Dart doesn’t provide multiple call function implementation in a same class. It throws one error that call is already defined like below :

Dart multiple call error

Similar tutorials :