考虑:
val foo: Int = 1
foo.toDouble() // ok
val bar = 2.toUInt()
bar.toDouble() // error!
这对我来说没有意义。为什么 UInot 不会toDouble
?(它也没有.toFloat
(。
文档说:
每种数字类型都支持以下转换:
- toByte((: Byte
- toShort((: Short
- toInt((: Int
- toLong((: Long
- toFloat((: Float
- 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 不被视为数字类型吗?还是别的什么?
根据此YouTrack请求,这似乎在1.3.30中出现。
1.3.30 最近刚刚被标记,似乎很快就会发布。
UInt 不被视为数字类型吗?
是的,它不会扩展Number
类。
Int
声明 :
class Int : Number, Comparable<Int>
UInt
声明 :
inline class UInt : Comparable<UInt>
从 Kotlin 版本 1.3.30 开始,UInt
具有toFloat
和toDouble
方法。
在最新版本中添加了支持 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() })
}
注意:UI 不会扩展数字类。
/**
* 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)