【问题标题】:Add an extensions function to Math class in kotlin向 kotlin 中的 Math 类添加扩展函数
【发布时间】:2017-08-17 20:03:27
【问题描述】:

我在 Kotlin 的 Math 类中添加了一个函数,但我无法使用它,我之前用 MutableList 做过这个,它工作但我不能用 Math 类做。

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

【问题讨论】:

标签: java kotlin extension-methods


【解决方案1】:

您不能在静态级别上在 Math 上使用此扩展,因为扩展仅适用于实例。 edit:由于 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多