Kotlin 使用 UInt 进行数组访问和常量

Kotlin use UInt for array access and constant

无符号数据类型可能适合数组访问。通常索引无论如何都是无符号的。但目前我不能直接这样做。例如。这段代码。

val foo = 1.toUInt()

"foo"[foo]

编译失败:

error: type mismatch: inferred type is UInt but Int was expected

处理此问题的最佳方法是什么?我当然可以:

val foo = 1.toUInt()

"foo"[foo.toInt()]

但这感觉有点不对劲。 UInt 无论如何都是内联 class 并且无论如何都会被删除为 Int - 所以我认为这不应该是必需的。有人为此看到了 kotlin/KEEP 吗? 还想知道如何定义无符号常量。不幸的是,构造函数是私有的,所以我不能这样做,例如

const val foo = UInt(42)

const val foo = 42.toUInt()

失败 42.toUInt() 不是常数值

在数组索引问题中,.toInt()是我找到的最好的方法。

声明一个常量,您可以将 "u" 附加到任何整数常量,或者 "uL" 附加到长常量,例如 42u1_000_000_000_000uL.

Unless/until 对此有内置支持,您可以轻松地自己添加。例如,对于标准数组:

operator fun <T> Array<T>.get(index: UInt) = this[index.toInt()]

对于 CharSequences(不是数组):

operator fun CharSequence.get(index: UInt) = this[index.toInt()]

在此范围内,您的 "foo"[foo] 工作正常!

(如果您使用了 IntArray &c,您还需要单独的重载。)