Why doesn't sumBy(selector) return Long?
That's a decision Kotlin team made. Since it's not possible to have return type overloads in Java the sumBy*
have to have different names depending on the return type.
It's easy enough to add your own sumByLong
though:
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
var sum = 0L
for (element in this) {
sum += selector(element)
}
return sum
}
You can also use the sum()
extension function which does have a Long
variant, in conjunction with map()
val totalLength = files.map { it.length() }.sum()
Or you could wrap this into an extension function, though I don't see much benefit over the inline version:
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
return map { selector(it) }.sum()
}
Optionally you can use fold
function.
val totalLength = files.fold(0L) { acc, it -> acc + it.length() }
It's not much longer than sumBy
code.