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.
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.
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.
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.
call()
method focused on a single responsibilityTo 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.