Callable Objects in Dart : Using call() Method, Example

Home » Dart » Callable Objects in Dart : Using call() Method, Example

In this tutorial, we’ll explore the use of callable objects in Dart programming language. This feature offers functional flexibility and expressive syntax.

Callable Objects in Dart : Using call() Method, Example

To enable your Dart class instance to function as if it were a callable function, simply implement the call() method within the class.

This method specifies the instance’s behavior, mimicking that of a regular function when invoked.

Expanding class versatility allows function-like use, boosting flexibility and intuitive codebase usage.

To make an object callable, you need to implement the call method within the class.

Dart Program Example:


void main() {
  
  var name = DemoFun();
  var output = name('Nikisurf!');
  print(output);
}

class DemoFun{
  
  String call(String name) => 'Name : $name';
  
}

The code demonstrates the use of Dart’s callable class feature.

The DemoFun class is callable via its implemented call method, enabling its instances to function similarly to functions. Invoking the DemoFun instance with the string argument ‘Nikisurf!’ returns the formatted string ‘Name: Nikisurf!’.

Name : Nikisurf!

Example

Open the Dart pad and Write the following code:

class Multiplier {
  int factor;

  Multiplier(this.factor);

  int call(int value) {
    return value * factor;
  }
}

void main() {
  
  var doubler = Multiplier(10);
  var result = doubler(3); // Equivalent to calling doubler.call(5)
  print(result); 
}

30

Advantages of Callable Objects in Dart

Functional Flexibility

By implementing the call method, classes become callable as if they were functions. This allows for a more functional programming style, enabling instances to be used in a function-like manner, enhancing code readability and conciseness.

The call() method enables any class instance that defines it to mimic a function, supporting features like parameters and return types, just as regular functions do.

Code Reusability

By defining callable behavior within classes, you can reuse instances across different contexts without the need for auxiliary methods or wrapper functions. This reusability reduces redundancy and promotes a more modular codebase.

Behavior

Callable objects grant developers the ability to specify custom behaviors upon instance invocation. This flexibility empowers classes to encapsulate logic and functionalities that extend beyond conventional method calls, delivering distinctive behaviors upon invocation.

Happy Dart coding!

You may also like...