1

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?

3
  • Are you familiar with Kotlin extensions? Commented Sep 8, 2022 at 23:06
  • While I can use Kotlin extensions to add instance methods to Instant, I can only use Kotlin extensions to add static methods if the class has a companion object, which Instant (being a Java class) does not :( Commented Sep 8, 2022 at 23:13
  • Instantiating Instant can 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) Commented Sep 9, 2022 at 18:22

1 Answer 1

2

The answer, it seems, is no. https://youtrack.jetbrains.com/issue/KT-11968

Can there be feature that will allow us to declare statically accessible members for Java classes too?

May 2022

We’re continuing to work on the design and planning to present a specific proposal for public review.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.