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

时间:2019-02-09 05:11:13

标签: kotlin unsigned

无符号数据类型可能适合数组访问。通常,索引无论如何都是无符号的。但是目前我无法直接执行此操作。例如。此代码。

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仍然是一个内联类,并且无论如何都会被擦除为Int-所以我认为这不是必需的。有人看到过Kotlin / KEEP吗? 也想知道如何定义无符号常量。不幸的是,构造函数是私有的,所以我不能这样做。

const val foo = UInt(42)

const val foo = 42.toUInt()

42.toUInt()失败不是恒定值

2 个答案:

答案 0 :(得分:3)

在数组索引问题中,.toInt()是我发现的最佳方法。

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

答案 1 :(得分:3)

Unless/until there's built-in support for this, you can easily add it yourself.  For example, for standard arrays:

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

And for CharSequences (which aren't arrays):

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

With that in scope, your "foo"[foo] works fine!

(You'd also need separate overloads for IntArray &c if you used those.)