本页尚未翻译,因此以英文显示。 参与翻译

sumByDouble · sumByInt

sumBy with the result already typed: a double or an int, no cast.

double sumByDouble<A>(double Function(A a) f, Iterable<A> iterable) int sumByInt<A>(int Function(A a) f, Iterable<A> iterable) Future<double> sumByDoubleAsync<A>(FutureOr<double> Function(A a) f, FxAsyncIterable<A> iterable) Future<int> sumByIntAsync<A>(FutureOr<int> Function(A a) f, FxAsyncIterable<A> iterable) double Fx<T>.sumByDouble(double Function(T a) f) // chain (sync) int Fx<T>.sumByInt(int Function(T a) f) // chain (sync) Future<double> FxAsync<T>.sumByDouble(FutureOr<double> Function(T a) f) // chain (async) Future<int> FxAsync<T>.sumByInt(FutureOr<int> Function(T a) f) // chain (async)

Lecture

sumBy returns num, because its selector may return either kind of number. That is right for a mixed column and a nuisance for a typed one: a gold rate stored in a double field, or a count stored in an int, needs .toDouble() or .toInt() after every sum. sumByDouble(f) and sumByInt(f) take a selector that already returns that type and give it back unchanged.

They also do slightly less work. sumBy keeps an int accumulator and switches to a double the first time a non-integer arrives, which costs a type test per element; these two start in the right accumulator and add. The addition order is the same left-to-right walk, so sumByDouble rounds exactly as sumBy does. Empty input returns 0.0 and 0, keeping the type.

fxdart extension (not part of FxTS). Three camelCase words, so by the naming rule there is no fx prefix on the top-level form.

Demo 1 · No cast

Demo 2 · Empty input and async

Try it yourself

Exercise: drop both casts by using the typed sums.

Related: sumBy — the num form for mixed columns · sum — the numbers themselves · averageBy — the mean of a selector