Kotlin的.indices是什么意思?

Roh*_*mar 6 kotlin

我想知道.indices的工作原理,这两个for循环之间的主要区别是什么。

for (arg in args)
    println(arg)
Run Code Online (Sandbox Code Playgroud)

要么

for (i in args.indices)
    println(args[i])
Run Code Online (Sandbox Code Playgroud)

withIndex()函数的用途是什么

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}
Run Code Online (Sandbox Code Playgroud)

zsm*_*b13 6

这些只是遍历数组的不同方式,具体取决于您需要在for循环体内访问的内容:当前元素(第一种情况),当前索引(第二种情况)或两者(第三种情况)。

如果您想知道它们如何在后台运行,您可以跳入Kotlin运行时的代码(IntelliJ中的Ctrl+ B),然后进行查找。

对于indices具体而言,这是非常简单的,它的实现为扩展属性,返回一个IntRange其中for环可以再叠代:

/**
 * Returns the range of valid indices for the array.
 */
public val <T> Array<out T>.indices: IntRange
    get() = IntRange(0, lastIndex)
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,对数组索引的迭代已优化并编译为等效于常规while循环索引,而没有创建“ IntRange”。 (3认同)