What's the difference between sumOf() and sumBy() in Kotlin 1.4?

4.9k Views Asked by At

How is the new sumOf() function in Kotlin 1.4 different from sumBy() or sumByDouble() functions?

2

There are 2 best solutions below

1
Ilya On BEST ANSWER

TLDR: there's no difference, and eventually sumBy/sumByDouble can be deprecated in favor of the single sumOf.

sumOf operation has overloads for different numeric types returned from the selector function. It's something that was impossible previously with the old type inference facility, so in order to handle different numeric types it was required to have functions with the different names: sumBy to sum ints, sumByDouble to sum doubles, etc.

When the new inference has finally arrived with the experimental support of overload resolution by selector lambda return type, we've decided not to overload the existing sumBy function, but to introduce a new operation sumOf. This way it has less chance of breaking something and is more consistent in naming with the new operations list.minOf/maxOf { selector }.

0
Mahozad On

As the Kotlin 1.4 changelog states:

... sumOf lets you handle sums of different types in the same way. it produces sums of the types Int, Long, Double, ... [depending on the return type of the given lambda].