Duration could support sum, sumBy

I had a bunch of parallel time measureTime (worked great!)
and thought I would be able to allWriters.awaitAll().sum() or .average()
I ended up with `

allWriters.awaitAll().sumBy { it.inMilliseconds.toInt() }.milliseconds

which wasn’t nearly as fun.

If you have a collection of durations, you can use fold function to sum them:

import kotlin.time.*
fun main() {
    val durations = listOf(1.seconds, 2.milliseconds, 3.minutes)
//sampleStart
    durations.fold(Duration.ZERO) { acc, d -> acc + d }
//sampleEnd
    .let { println(it.toIsoString()) }
}

or, with a method reference:

import kotlin.time.*
fun main() {
    val durations = listOf(1.seconds, 2.milliseconds, 3.minutes)
//sampleStart
    durations.fold(Duration.ZERO, Duration::plus)
//sampleEnd
    .let { println(it.toIsoString()) }
}
1 Like

Great workarounds, thank you!

(I still have a FR for .sum() to work out of the box, for the hypothetical next person who runs into this.)

fun Iterable<Duration>.sum(): Duration {
    var sum: Duration = Duration.ZERO
    for (element in this) {
        sum += element
    }
    return sum
}

Why not using fold like ilya proposed?

Mostly because I wanted to think about it in the same way as other numbers, I was surprised I couldn’t do sum(), and I like it how often kotlin doesn’t surprise me!