Kotlin Duration API: custom DurationUnit

Currently we can only use existing extensions: Int.minutes, Int.seconds, etc. What if I want to declare my own DurationUnit? For example, in Minecraft development everything is measured in ticks, 1 second == 20 ticks. There’s no way to do this right now. Duration constructor is internal, and Int.toDuration accepts fixed enum values. In Java 8 Date/Time API we can implement TemporalUnit interface and use, for example, Instant#truncatedTo with our custom TemporalUnit. Can this be achieved in Kotlin Duration and time measurement API?

If you introduce Int.ticks and Duration.inTicks extension properties, would that be enough to cover your use case?

1 Like

Yes, but I couldn’t find a way to do this

Just look at how these extensions are defined for Duration type and declare your own in your package, e.g.:

import kotlin.time.*

@ExperimentalTime
val Int.ticks: Duration get() = this.seconds / 20
@ExperimentalTime
val Duration.inTicks: Double get() = this.inSeconds * 20

fun main() {
    println(15.ticks)
    println(1.milliseconds.inTicks)
}

Didn’t think about using existing extensions. Thanks!