gpt4 book ai didi

kotlin - .indices 在 kotlin 中的含义是什么?

转载 作者:IT老高 更新时间:2023-10-28 13:47:33 26 4
gpt4 key购买 nike

我想知道 .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具体来说,这很简单,它被实现为 extension property返回一个 IntRange ,然后 for 循环可以对其进行迭代:

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

关于kotlin - .indices 在 kotlin 中的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44303914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com