What are Dart Callable Classes?
In Dart, callable classes are a special kind of classes that can be invoked like functions. This is achieved by defining a call() method within the class. The call() method makes an instance of the class behave as if it were a function, enabling you to “call” the instance with the same syntax you’d use for a function call.
This feature can be particularly useful when you want to pass a class instance around in your code where a function is expected, or when you want to maintain a state within an object that also needs to behave like a function.
This article is the part of “The Flutter Foundation: A Comprehensive Guide for Technical Interviews and Beyond”! You can download it free! @ https://chetanakarte.gumroad.com/l/the_flutter_foundation
Example of a Callable Class:
class Greeter {
final String greeting;
Greeter(this.greeting);
String call(String name) => '$greeting, $name!';
}
void main() {
var helloGreeter = Greeter('Hello');
print(helloGreeter('World')); // Outputs: Hello, World!
var hiGreeter = Greeter('Hi');
print(hiGreeter('John')); // Outputs: Hi, John!
}
In this example, Greeter is a callable class because it implements the call() method. When you create an instance of Greeter and then use it like a function (helloGreeter(‘World’)), the call() method is invoked.
Use Cases for Callable Classes:
· Event Handlers: When an object needs to maintain state related to how it handles events, a callable class can encapsulate both the state and the event-handling logic.
· Strategies and Policies: When implementing strategy patterns or policy objects that might change dynamically at runtime, callable classes provide a neat way to encapsulate each strategy or policy’s logic.
· Function Objects with State: In scenarios where a function needs to maintain state across invocations, using a callable class allows you to keep that state within the object, making the code more organized and reusable.
Callable classes offer a blend of object-oriented and functional programming paradigms, allowing for more flexible and expressive code designs.