I've defined an extension:
extension MyIterable<T extends num> on Iterable<T> {
T sum() => reduce((v, e) => v e); // Error
}
Why is v e
not considered T
, why is there an error?
The return type 'num' isn't a 'T', as required by the closure's context.
I'm using it in the main
:
void main() {
int a = MyIterable<int>([1, 2]).sum();
double b = MyIterable<double>([1.0, 2]).sum();
num c = MyIterable<num>([1.0, 2]).sum();
}
CodePudding user response:
Although v
and e
are statically known to be T
, which is some subtype of num
, the exact subtype isn't known, so v e
is only statically known to conform to num.operator
. Consequently, the result is num
(the base type), not necessarily a T
(the more specific subtype).
In this case, I think you'll probably need to add an as T
explicit cast.