kotlin.time.Duration - builders from string?

I found myself typing in a lot of 12.hours + 15.minutes + 7.seconds style durations, and ended up with a common helper function that convert [[hh:]mm:]ss] String to Duration. It isn’t pretty, but it is much more compact.

It might help with Duration adoption to have some common function that built durations out of ISO standard strings. I enjoy what moment.js did with the strict flag on.

We’re considering to provide a function that could parse Duration both from its human-readable representation, like returned by toString(), and from the ISO representation returned by toIsoString(); see this KEEP comment. Whether it should be a String extension or a Duration companion object member is to be discussed.

Fantastic! I have a slight leaning towards Duration, keep String uncluttered, but that is a minor preference. I’m very much about the “strict” mode that moment.js adopted.
Glad to hear it is already under consideration, thank you!

1 Like

What would be the reasons for making it an extension rather than a companion object method, which to me would seem the obvious choice?

About the only one I can think of would be the fact that use of an extension (especially if implemented as a property) would be slightly less verbose. But putting it in the companion to Duration would make it clear which domain it belongs in, and minimize namespace clutter.

Extensions are great for adding functionality to classes not part of the Kotlin library itself, but in some contexts I have seen what I consider to be overuse, leading to name confusion.