Lucca
Lucca

Reputation: 195

Is it possible to extend a class with a static method in Kotlin or Java?

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?

Upvotes: 1

Views: 276

Answers (1)

Lucca
Lucca

Reputation: 195

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.

Upvotes: 2

Related Questions