Kotlin 为什么';您是否没有toDouble()?

Kotlin 为什么';您是否没有toDouble()?,kotlin,Kotlin,考虑: val foo: Int = 1 foo.toDouble() // ok val bar = 2.toUInt() bar.toDouble() // error! 这对我来说毫无意义。你为什么不让加倍?(它也没有.toFloat) : 每种数字类型都支持以下转换: toByte():字节 toShort():Short toInt():Int toLong():长 toFloat():浮动 toDouble():Double toChar():Char 所以这应该是可能的。我

考虑:

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

val bar = 2.toUInt()
bar.toDouble() // error!
这对我来说毫无意义。你为什么不让
加倍
?(它也没有
.toFloat

:

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

  • toByte():字节
  • toShort():Short
  • toInt():Int
  • toLong():长
  • toFloat():浮动
  • toDouble():Double
  • toChar():Char
所以这应该是可能的。我得到的错误是:

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是否不被视为数字类型?还是别的什么

UInt是否不被视为数字类型

是的,它不扩展类

声明
Int

class Int : Number, Comparable<Int>
inline class UInt : Comparable<UInt>


从Kotlin版本1.3.30开始
UInt
toFloat
toDouble
方法。

这似乎出现在1.3.30中,根据


1.3.30刚刚发布,似乎很快就会发布。

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

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

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不扩展数字类


谢谢,这太令人惊讶了。有没有其他方法将
UInt
转换为
Double
的方法?@raket1111尝试
bar.toLong.toDouble()
可能相关:某些体系结构(特别是x86)没有本机指令将无符号整数转换为浮点,只有有符号整数。(AVX512最终为x86添加了这一功能,但它仍然没有广泛使用,距离成为基准还有很长的路要走)。在可能的情况下,零扩展到更宽的有符号整数类型是无符号->浮点或双精度的最简单实现,但对于64位无符号整数,需要特殊技巧。也许科特林想避免这样?但考虑到它运行在JVM或Javascript之上,可能还有其他东西。@PeterCordes我怀疑是否有任何语言希望将自身局限于单一体系结构的缺点。我的意思是,即使是C也允许这样做:)但是有趣的信息,谢谢。
/**
 * 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)