Created
April 20, 2020 17:07
-
-
Save Abhinav1217/f9c65c980cf26d90b208c8fd3ac72464 to your computer and use it in GitHub Desktop.
sumByLong() polyfill and similar options.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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