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

Add an extensions function to Math class in kotlin

我在 Kotlin 中向 Math class 添加了一个函数,但我无法使用它,我之前用 MutableList 做过这个并且它有效但我不能用Math class.

fun Math.divideWithSubtract(num1: Int, num2: Int) = 
Math.exp(Math.log(num1.toDouble())) - Math.exp(Math.log(num2.toDouble()))

您不能像静态 java 方法那样使用它,而只能在 Math 对象上使用它。这就是它在 MutableList 上起作用的原因,因为您在 上使用了它列表.

为什么要在这里扩展 Math?扩展是有意义的,当你有一个接收器类型(比如 String),你想要扩展它的 个实例 。 Math 只是一个 util class 并且 无法实例化,即无法为函数提供适当的 receiver

只需在顶层创建此方法,例如:

fun divideWithSubtract(num1: Int, num2: Int) =
        Math.exp(Math.log(num1.toDouble())) - Math.exp(Math.log(num2.toDouble()))

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

如果你真的想将该方法作为扩展,你应该改为扩展 Int :

fun Int.divideWithSubtract(otherInt: Int) = 
    Math.exp(Math.log(this.toDouble())) - Math.exp(Math.log(otherInt.toDouble()))

你会像这样使用它:

val result = 156.divideWithSubstract(15) //:Double

如果你真的想要静态方法,在 Java 和 Kotlin 中,你总是可以在 kotlin 文件中的包级别定义任何方法。

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

参见:Package level functions in the official doc