Start Coding

Topics

Dart Callable Classes

Callable classes in Dart provide a unique way to create objects that can be invoked like functions. This powerful feature enhances code flexibility and expressiveness.

What are Callable Classes?

In Dart, a callable class is a class that defines a call() method. This special method allows instances of the class to be invoked as if they were functions.

Syntax and Usage

To create a callable class, define a call() method within your class. This method can accept parameters and return values just like regular functions.


class Calculator {
  int call(int a, int b) => a + b;
}

void main() {
  var calc = Calculator();
  print(calc(3, 4)); // Output: 7
}
    

In this example, the Calculator class becomes callable, allowing us to use its instances as functions.

Benefits and Use Cases

  • Encapsulate complex logic within objects
  • Create function-like objects with state
  • Implement strategy patterns more elegantly
  • Enhance code readability in functional programming scenarios

Advanced Example: Configurable Formatter


class TextFormatter {
  final String prefix;
  final String suffix;

  TextFormatter({this.prefix = '', this.suffix = ''});

  String call(String text) => '$prefix$text$suffix';
}

void main() {
  var boldFormatter = TextFormatter(prefix: '**', suffix: '**');
  var italicFormatter = TextFormatter(prefix: '_', suffix: '_');

  print(boldFormatter('Hello')); // Output: **Hello**
  print(italicFormatter('World')); // Output: _World_
}
    

This example demonstrates how callable classes can be used to create configurable, reusable formatting functions.

Best Practices

  • Use callable classes when you need function-like objects with state
  • Keep the call() method focused on a single responsibility
  • Consider using Dart Generics for more flexible callable classes
  • Combine with Dart Higher-Order Functions for advanced functional programming patterns

Related Concepts

To further enhance your understanding of Dart's object-oriented and functional programming features, explore these related topics:

Mastering callable classes in Dart opens up new possibilities for creating flexible and expressive code. By combining the power of objects with the simplicity of function calls, you can write more elegant and maintainable Dart applications.