为什么Kotlin不支持无符号整数?

sta*_*abs 11 types language-design unsigned-integer kotlin

我刚刚遇到一种情况,其中无符号整数本来就非常有用(例如,任何负值都没有意义等等).令人惊讶的是,我发现Kotlin不支持无符号整数 - 并且似乎没有其他任何关于为什么(即使我看过).

我错过了什么吗?

gil*_*dor 7

从 Kotlin 1.3 开始,无符号类型可用并且基于内联类功能。

请参阅 1.3-M1 版本的“无符号整数类型”部分:https : //blog.jetbrains.com/kotlin/2018/07/see-whats-coming-in-kotlin-1-3-m1/


jrt*_*ell 6

为什么Kotlin没有原生的无符号类型

这是因为正如这个问题所示,Java没有内置的无符号类型.

当在JVM上使用时,Kotlin编译为Java字节码,因此Java的这种限制也适用于Kotlin.

解决方法

您可以使用Integer和Long的实用程序方法将值作为无符号链接进行操作,但这仍然将值存储为内部签名.

您还可以编写一个包含值的实用程序类,其行为类似于unsigned int类型,但这可能比使用上述方法慢.


Wil*_*zel 5

作为glidor正确提到的,对应的无符号ByteShortIntLong确实存在,因为科特林1.3 ,但要小心,因为他们仍然是 实验

文档

kotlin.UByte:无符号的8位整数,范围从0到255
kotlin.UShort:无符号的16位整数,范围从0到65535
kotlin.UInt:无符号的32位整数,范围从0到2 ^ 32-1
kotlin.ULong:无符号的64位整数,范围从0到2 ^ 64-1

用法

// You can define unsigned types using literal suffixes
val uint = 42u 

// You can convert signed types to unsigned and vice versa via stdlib extensions:
val int = uint.toInt()
val uint = int.toUInt()
Run Code Online (Sandbox Code Playgroud)