I want to know actually how .indices works and what is the main difference is between this two for loops.

for (arg in args)
    println(arg)

or

for (i in args.indices)
    println(args[i])

那么withIndex()函数有什么用处呢?

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

推荐答案

这些只是迭代数组的不同方式,具体取决于您在for循环的主体中需要访问的内容:当前元素(第一个 case )、当前索引(第二个 case )或两者(第三个 case ).

如果您想知道它们在幕后是如何工作的,只需跳到Kotlin运行时的代码(IntelliJ中的Ctrl+B),就能找到答案.

For indices specifically, this is pretty simple, it's implemented as an extension property that returns an IntRange which a for loop can then iterate over:

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

Kotlin相关问答推荐

判断字符串是否除了.&" ",","@""""

将带大括号和不带大括号的Lambda值赋给@Composable函数

如何进行基于lambda/谓词的两个列表的交集?

有没有一种简单的方法来识别物体?

哪个更好? Integer.valueOf(readLine()) 或 readLine()!!.toInt()

扩展属性委托给实例属性

ActivityResultContracts TakePicture 结果总是返回 false

第二个协程永远不会执行

如何从 Firestore 查询中排除元素?

Kotlin:找不到符号类片段或其他 android 类

Kotlin:什么是 kotlin.String!类型

Kotlin:子构造函数如何使用其父构造函数的辅助构造函数?

ObserveForver是否了解生命周期?

如何为kotlin异常生成SerialVersionId?

参数不匹配;SimpleXML

如何从协程范围返回值

Android Kotlin .visibility

判断EditText是否为空kotlin android

Kotlin 中内部可见性修饰符的范围

Kotlin - 错误:Could not find or load main class _DefaultPackage