D
OOP & SOLIDMedium30 XP3 min read

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

dartCallable class and operator overloading
Output
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.

#callable#operator-overloading#call-method#dart