I would like to create a Java Instant from a Long representing a nanosecond epoch. While Instant has nanosecond precision, the only way to do this would be to use the nanoAdjustment argument of Instant.ofEpochSecond:
val nanos: Long
val instant = Instant.ofEpochSecond(0, nanos)
But it would be more convenient and readable if I could simply do:
val nanos: Long
val instant = Instant.ofEpochNanos(nanos)
To achieve this, the only solution I could think of was
package util
object Instant {
/** Obtains an [Instant] from nanoseconds. */
fun ofEpochNanos(nanos: Long): Instant = Instant.ofEpochSecond(0, nanos)
}
Then I can call Instant.ofEpochNanos, but this is a hack. When I import the util package above and import java.time.Instant, I will end up with two unrelated objects with the same name: the Instant object above, and the Instant class from java.time.
So, is it possible to actually extend a class with a static method?
Instant, I can only use Kotlin extensions to add static methods if the class has a companion object, whichInstant(being a Java class) does not :(Instantcan be considered a separate responsibility; just make it a separate (factory) class. It keeps the code clean and simple; no need to hack your way into a class or interface that is not yours. As for readability, I see no problem in:val instant = InstantFactory.createFromNanos(nanos)