Skip to content

Instantly share code, notes, and snippets.

@Abhinav1217
Created April 20, 2020 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abhinav1217/f9c65c980cf26d90b208c8fd3ac72464 to your computer and use it in GitHub Desktop.
Save Abhinav1217/f9c65c980cf26d90b208c8fd3ac72464 to your computer and use it in GitHub Desktop.
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