【问题标题】:Why doesn't UInt have a toDouble()?为什么 UInt 没有 toDouble()?
【发布时间】:2019-04-11 16:06:15
【问题描述】:

考虑:

val foo: Int = 1
foo.toDouble() // ok

val bar = 2.toUInt()
bar.toDouble() // error!

这对我来说没有意义。为什么 UInt 没有toDouble? (它也没有.toFloat)。

The docs say:

每种数字类型都支持以下转换:

  • toByte(): 字节
  • toShort():短
  • toInt(): 整数
  • toLong(): 长
  • toFloat(): 浮点数
  • toDouble(): 双倍
  • toChar(): 字符

所以应该可以。我得到的错误是:

Error:(11, 4) Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
@InlineOnly public inline fun String.toDouble(): Double defined in kotlin.text

UInt 不被视为数字类型吗?还是别的什么?

【问题讨论】:

  • 可能相关:某些体系结构(尤其是 x86)没有将无符号整数转换为浮点的本机机器指令,只有有符号。 (AVX512 最终为 x86 添加了该功能,但它仍然没有被广泛使用并且非常远未成为基线)。如果可能的话,零扩展为更广泛的有符号整数类型是迄今为止最简单的 unsigned->float 或 double 实现,但对于 64 位无符号整数,您需要特殊技巧。也许 Kotlin 想避免这种情况?但考虑到它运行在 JVM 或 Javascript 之上,也许还有别的东西。
  • @PeterCordes 我怀疑任何语言都希望将自己限制在单一架构的缺点上。我的意思是即使 C 也允许这样做 :) 但是有趣的信息,谢谢。

标签: kotlin


【解决方案1】:

根据this YouTrack request,这似乎将在 1.3.30 中推出。

1.3.30 只是 recently tagged,似乎很快就会发布。

【讨论】:

    【解决方案2】:

    UInt 不被认为是数字类型吗?

    是的,它不扩展 Number 类。

    Int的声明:

    class Int : Number, Comparable<Int>
    

    UInt的声明:

    inline class UInt : Comparable<UInt>
    

    从 Kotlin 版本 1.3.30 开始,UInt 具有 toFloattoDouble 方法。

    【讨论】:

    • 谢谢,这太令人惊讶了。有没有办法以其他方式将UInt 转换为Double
    • @Rakete1111 试试bar.toLong.toDouble()
    【解决方案3】:

    在最新版本 1.3.30 中添加了支持。

    此版本 (More) 支持对无符号类型和无符号类型数组的更多操作,这些操作反映了常规数字类型的操作:

    fun main() {
        val u1 = 2_147_483_649u
        val u2 = 4_000_000_000u
        println(u1.toDouble())
        println(minOf(u1, u2))
    
        val array: UIntArray = uintArrayOf(u1, u2)
        println(array.max())
        println(array.all { it > Int.MAX_VALUE.toUInt() })
    }    
    

    注意:UInt 不扩展 Number 类。

    /**
     * Converts this [UInt] value to [Double].
     *
     * The resulting `Double` value represents the same numerical value as this `UInt`.
     */
    @kotlin.internal.InlineOnly
    public inline fun toDouble(): Double = uintToDouble(data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多