什么是.indices在kotlin中的含义?
我想知道.indices是如何工作的,这两个for循环之间的主要区别是什么。
for (arg in args) println(arg)
要么
for (i in args.indices) println(args[i])
withIndex()
函数有什么用处
for ((index, value) in array.withIndex()) { println("the element at $index is $value") }
这些只是对数组迭代的不同方法,具体取决于您在for
循环体内需要访问的内容:当前元素(第一种情况),当前索引(第二种情况)或两者(第三种情况)。
如果你想知道他们是如何工作的,你可以跳到Kotlin运行时的代码(IntelliJ中的Ctrl + B ),并找出答案。
特别是对于indices
,这非常简单,它被实现为一个扩展属性 ,它返回一个for
循环可以迭代的IntRange
:
/** * Returns the range of valid indices for the array. */ public val <T> Array<out T>.indices: IntRange get() = IntRange(0, lastIndex)
正如文档中所提到的, 索引是列表中的索引值。
返回此集合有效索引的IntRange。
有关更多详细信息,请参阅文档