Hi! I was missing a collection function `sumOfOrNu...
# kontributors
b
Hi! I was missing a collection function
sumOfOrNull
so I wrote my own very simple one:
Copy code
inline fun <T> Iterable<T>.sumOfOrNull(selector: (T) -> Double?): Double? =
    this.mapNotNull(selector)
        .reduceOrNull { acc, i -> acc + i }
Does it make sense to add it to the standard library? Is this even suitable? I see the standard library uses mostly iterators,
for
or
while
, and not that much high level stuff (I guess due to performance?)
a
Do you really need an
orNull
variant?
sumOf
doesn't throw an exception if the iterable is empty.
b
Yes, I need an
orNull
variant. I am summing over a List<Double?> and if all elements are null, the result should be null not 0. Regular
sumOf
would return 0.
Well technically it's not a List<Double?>, but my selector returns a Double?
r
Could you not simply use something like
sumByDouble{ it ?: 0.0 }
b
No. In my use case
null
and
0
is semantically different
r
Oh I see, you want your sum function to return null if all elements are null?
b
Exactly. Just like reduceOrNull or all of the other functions that work like this 🙂
a
Combining a specific type of filtering and summing seems like a very niche use case. It's probably not common enough to add to the stdlib.
âž• 1
190 Views