How can one add static methods to Java classes in Kotlin

六月ゝ 毕业季﹏ 提交于 2019-12-17 16:24:34

问题


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...


回答1:


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

This idea is very popular in the Kotlin community, so I bet it'll be in soon enough.




回答2:


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.




回答3:


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()


来源:https://stackoverflow.com/questions/33911457/how-can-one-add-static-methods-to-java-classes-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!