bool allTrue(Iterable<bool> bools) => bools.reduce(&&);
Is the reason that one cannot do the above that operator tear-offs are not allowed in dart, cf. https://github.com/dart-lang/sdk/issues/27518. And to actually make it work, is there a nicer way than to use the lambda as in
bool allTrue(Iterable<bool> bools) => bools.reduce((a, b) => a && b);
?
CodePudding user response:
There are lots of reasons it's not allowed.
Dart doesn't allow operator tear-offs. You can tear off [1].add
, but not 1.
.
Those are both instance methods. but there is no allowed syntax for naming the operator methods, only for invoking them.
It's definitely possible that Dart could add syntax to allow 1.
to return, effectively, (num other) => 1 other
. Just hasn't happened yet.
What you write is different. You write &&
by itself, not as a member of any instance, and expect (a, b) => a && b
. That's not an operator tear-off, that's just some kind of abstraction over operands.
Again, there is no strong reason Dart couldn't allow something like that, say any unary or binary operator as a full expression, e.g., in parentheses like ( )
or (~)
, would effectively mean (a, b) => a b
or (a) => ~a
, with types inferred from the context when possible.
Hasn't happened yet, and not really on anybody's list of priorities.
And then there is the problem that &&
, ||
and ??
are short-circuiting operators. Even if you do (&&)
to get (a, b) => a && b
, calling that function is not the same as using &&
on two expressions, because the second argument is always evaluated in the function call.
Those operators are just not good candidates for allowing "operator-functionalization". You would use (&)
and (|)
instead, since they work exactly the same.
It's unlikely that even if Dart allowed ( )
, it would also allow (&&)
.
CodePudding user response:
uh...
Yes (and no)
Sorry. That is a bit short for an answer, but what do you expect. It does not work this way. In any compiled language I know, and that includes Dart. Not because of that specific issue though. In general.
That said, operators are not functions. For example, they might short-circuit, something functions cannot do. If you could "tear off" an operator, how would that work? Again, that is the case in almost all compiled languages, nothing special to see here for Dart.