What are callable classes and operator overloading in Dart?
TL;DR: A callable class implements the call() method, letting instances be invoked like functions. Operator overloading redefines +, ==, [], etc. for custom types. Both improve DSL-like APIs.
Full Answer
Callable Classes
Any class with a call() method can be used like a function. Flutter uses this for gesture recognizers and some state management patterns. It's useful for function objects that need state or multiple methods.
Operator Overloading
Dart allows overloading: +, -, *, /, ~/, %, ^, &, |, <<, >>, >>>, ==, <, >, <=, >=, [], []=, ~. The == override must also override hashCode.
Always override hashCode when overriding ==. If a == b is true, then a.hashCode must equal b.hashCode, or HashMap/Set will break.
Code Examples
21 Vector2D(4.0, 6.0) Vector2D(2.0, 4.0) true
Common Mistakes
- โOverriding == without overriding hashCode โ objects won't work correctly in Map/Set
- โOverloading operators in ways that violate mathematical intuition โ makes code harder to read
Interview Tip
Dart's == override requirement for hashCode is a classic interview question. Explain why: Sets and Maps use hashCode first to find the bucket, then == to confirm equality.