How to declare a generic operator in Dart strong mode?

Viewed 592

Dart lets me declare generic methods, e.g. T first<T>(List<T> ts). But how can I declare a generic type for methods that are operators, like operator |? Is there a syntax for this (and is it documented somewhere)?

2 Answers

Dart operators cannot be generic.

The primary reason is that there is no syntax for providing the type. With a generic method, you can call it as o.foo<int>(...) to explicitly pass the type argument. There is no place to put the <int> in an operator (no, we do not want to allow x+<int>42, that just reads horribly!)

Also, if you think of the type argument as an extra argument, operators are already restricted to a specific number of arguments. The same problem applies to getters and setters, they can't take extra arguments (practically or syntactically), so they can't be generic.

Related