Eric
Eric

Reputation: 17536

How can one add static methods to Java classes in Kotlin

Is it possible to add a new static method to the java.lang.Math class in Kotlin? Usually, such things are possible in Kotlin thanks to Kotlin Extensions.

I already tried doing the following in a file I made called Extensions.kt:

fun Math.Companion.clamp(value:Double,minValue:Double,maxValue:Double):Double
{
    return Math.max(Math.min(value,maxValue),minValue)
}

but Math.Companion could not be resolved...

Upvotes: 61

Views: 7829

Answers (4)

Hrudhay
Hrudhay

Reputation: 326

Update on top of other answers: Static extensions will be available right after 2.0

Official announement: kotlin conf 2023

Upvotes: 2

Ky -
Ky -

Reputation: 32083

As of Kotlin 1.3, this is not possible. However, it's being considered for a future release!

To help this feature get implemented, go vote on this issue: https://youtrack.jetbrains.com/issue/KT-11968

Because all proposals are basically in limbo right now, I wouldn't hold my breath that this will get in any time soon

Upvotes: 54

Miguel A. Gabriel
Miguel A. Gabriel

Reputation: 323

As of Kotlin 1.2 it is still not possible.

As a workaround, to statically "extend" Environment class I am currently using:

Class EnvironmentExtensions {
    companion object {
        @JvmStatic
        fun getSomething(): File {
            ...
            return Environment.something()
        }
    }
}

It is not an ideal solution but IntelliJ/Android Studio code completion helps with the usage:

val something = EnvironmentExtensions.getSomething()

Upvotes: 3

aga
aga

Reputation: 29416

I think this is not possible. Documentation says the following:

If a class has a companion object defined, you can also define extension functions and properties for the companion object.

The Math class is a Java class, not a Kotlin one and does not have a companion object in it. You can add a clamp method to the Double class instead.

Upvotes: 15

Related Questions