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.)