Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin将UInt用于阵列访问和常量_Kotlin_Unsigned - Fatal编程技术网

Kotlin将UInt用于阵列访问和常量

Kotlin将UInt用于阵列访问和常量,kotlin,unsigned,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无论

对于数组访问,无符号数据类型可能很好。通常索引都是无符号的。但目前我无法直接做到这一点。例如,此代码

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)


使用
42失败。toUInt()
不是一个常量值

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


声明常量时,可以将“u”附加到任何整数常量,或将“uL”附加到长常量,如
42u
1_000_000_000_000uL

,除非/直到有内置支持,否则您可以轻松地自己添加它。例如,对于标准阵列:

operator fun <T> Array<T>.get(index: UInt) = this[index.toInt()]
在这个范围内,您的
“foo”[foo]
工作正常


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

谢谢!希望它能在某个时候进入标准库
operator fun <T> Array<T>.get(index: UInt) = this[index.toInt()]
operator fun CharSequence.get(index: UInt) = this[index.toInt()]