Paul Brauner
Paul Brauner

Reputation: 1347

How to declare a generic operator in Dart strong mode?

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)?

Upvotes: 4

Views: 880

Answers (2)

lrn
lrn

Reputation: 71763

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.

Upvotes: 3

matanlurey
matanlurey

Reputation: 8614

Generic operators are not supported at this time.

Feel free to "thumbs up" this feature request: https://github.com/dart-lang/sdk/issues/30048

Upvotes: 2

Related Questions