在kotlin中为Math类添加扩展函数

Ali*_*Urz 6 java extension-methods kotlin

Math在Kotlin中添加了一个函数,但是我无法使用它,我之前使用它MutableList并且它有效但我无法用Math类来完成它.

fun Math.divideWithSubtract(num1: Int, num2: Int) = 
Math.exp(Math.log(num1.toDouble())) - Math.exp(Math.log(num2.toDouble()))
Run Code Online (Sandbox Code Playgroud)

Xal*_*rax 8

您不能在静态级别上对Math使用此扩展,因为扩展仅适用于实例.编辑:由于Math无法实例化,因此您将无法使用扩展.

如果你真的想要这个方法作为扩展,你应该扩展Int:

fun Int.divideWithSubtract(otherInt: Int) = 
    Math.exp(Math.log(this.toDouble())) - Math.exp(Math.log(otherInt.toDouble()))
Run Code Online (Sandbox Code Playgroud)

你会像这样使用它:

val result = 156.divideWithSubstract(15) //:Double
Run Code Online (Sandbox Code Playgroud)

如果你真的想要使用static-ish方法,那么在Java和Kotlin中,你总是可以在kotlin文件中定义包级别的任何方法.

因此,文件中的某些doSomething(args)方法Util.kt可以在任何Kotlin文件中的任何位置访问,您必须使用UtilKt.doSomething()Java 调用.

请参阅:官方文档中的包级别功能