【问题标题】:Kotlin math vs MathKotlin 数学与数学
【发布时间】:2019-09-13 03:55:55
【问题描述】:

我已阅读 What is the Kotlin exponent operator 并尝试通过在 Android Studio REPL Kotlin 模式下编写 val t1 = 23.0 然后 print (t1!!.pow(4.9)) 来遵循它的答案,并获得第二个 错误:未解决的参考:pow。通过搜索 Kotlin 幂函数在其他地方找到的代码可以正常工作print (Math.pow(t1,4.0))。我很困惑,但发现那个帖子Unresolved reference: pow in Eclipse using Kotlin,当我做import kotlin.math.pow时,下一个print (t1.pow(4.9))开始给出一个数字。我还注意到import kotlin.Math.pow 给出了 error: unresolved reference: Math,所以
1. 为什么 Math.pow 却导入 kotlin.math?
2. 我可以使用扩展函数 pow 而不在 REPL 中导入类似 t1.math.pow(2.3) 的东西(因为它给出了 error: unresolved reference: math

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    当使用Math.pow(10.0, 2.0)

    println(Math.pow(10.0, 2.0)) // "100.0"
    

    Math 指的是java.lang.Math 类。

    您可以通过调用验证这一点

    println(Math::class) // "java.lang.Math"
    

    在这种情况下,不需要导入任何东西,因为java.lang包是默认导入的。


    当使用10.0.pow(2)

    println(10.0.pow(2)) // "100.0"
    

    pow指的是fun Double.pow(x: Double): Double,需要从kotlin.math.pow显式导入的Kotlin扩展函数:

    import kotlin.math.pow
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多