Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 600
Mahozad Avatar asked Jul 10 '20 07:07

Mahozad


2 Answers

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 }.

like image 156
Ilya Avatar answered Nov 13 '22 00:11

Ilya


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].

like image 24
Mahozad Avatar answered Nov 13 '22 00:11

Mahozad