Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sumByLong() polyfill and similar options.
// Kotlin have sumBy:Int and sumByDouble:Double but many of us work with Long which is missing.
// This is an implementation based on stdlib for sumbydouble
// Save this in your util to make this accessable.
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
var sum = 0L
for (element in this) {
sum += selector(element)
}
return sum
}
// Following is an implementation using fold()
// This have similar benchmarks. This is a trick not a utility
// Use this trick if you don't want to have a project wide function.
val total = files.fold(0L) { sum, element -> sum + element }
// Then here is what you are probably used to see all over the place
val total = files.map { element }.sum()
// or if some one is smarter he would have converted this to utility function
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
return map { selector(it) }.sum()
}
// But this technique is more resource intensive. So even though this is quite popular
// Using this is not good.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment