What is a Callable Class?
A callable class is a class that defines a call method. When an instance of such a class is invoked like a function (i.e., using parentheses with arguments), the call method is executed. This feature allows objects to behave like functions, enabling you to use them as callbacks, create function‑like objects with state, and build expressive APIs.
Defining a Callable Class
To make a class callable, simply add a method named call. It can have any parameters and return type. The method can be synchronous or asynchronous.
Call Method with Parameters
The call method can accept parameters, just like a regular function. This allows you to use your callable objects as custom functions.
Named and Optional Parameters
You can use all Dart parameter features in the call method: positional, optional, named, required, etc. This makes callable objects flexible.
Callable Classes as Callbacks
Because callable objects behave like functions, they can be used anywhere a function is expected, such as callbacks for forEach, map, or custom APIs.
Stateful Callable Objects
One powerful aspect of callable classes is that they can maintain state across invocations. This is like a closure, but with explicit fields and methods.
Generic Callable Classes
You can make your callable classes generic, allowing them to work with different types while preserving type safety.
Async Callable Classes
The call method can be async or return a Future, making the object callable asynchronously.
Use Cases
- Function‑like objects with configuration: e.g., multipliers, loggers with level.
- Stateful callbacks: counters, accumulators, caches.
- Fluent DSLs: design APIs where objects can be called with parentheses.
- Dependency injection: replace simple functions with more complex objects.
- Mocking: create test‑friendly callable objects that track calls.
Best Practices
- Use callable classes when you need state or configuration that a simple function cannot provide.
- Keep the
callmethod focused; avoid side effects unless intended.
- Keep the
- Document the expected usage (especially if the object is used as a callback).
- Use generic callable classes to maintain type safety when working with multiple types.
Complete Example
Key Takeaways
- Implement the
callmethod to make a class callable.
- Implement the
- Callable objects can be used anywhere a function is expected.
- They can have state, configuration, and generic parameters.
- Use callable classes for function‑like objects that need more than just a function.