在 Kotlin 中更改 for 循环索引 [英] Change for loop index in Kotlin

查看:59
本文介绍了在 Kotlin 中更改 for 循环索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Kotlin 中修改循环变量?

How can I modify the loop variable in Kotlin?

对于我的特殊情况,我有一个 for 循环,在该循环中,对于某些条件,我想跳过下一次迭代:

For my particular case, I have a for-loop in which, for certain conditions, I want to skip the next iteration:

for(i in 0..n) {
  // ...
  if(someCond) {
    i++ // Skip the next iteration
  }
}

然而,当我尝试这个时,我被告知val 不能重新分配".

However, when I try this, I'm told that "val cannot be reassigned".

推荐答案

你不能改变当前元素,你需要使用 while 循环来代替:

You can't mutate the current element, you would need to use a while loop instead:

var i = 0
while (i <= n) {
    // do something        
    
    if (someCond) {
        i++ // Skip the next iteration
    }

    i++
}

你想做什么?有可能有一种更惯用的方法来做到这一点.

What are you trying to do? There is a chance there is a more idiomatic way to do this.

如果您可以重构此逻辑以跳过当前迭代,为什么不使用continue:

If you could restructure this logic to skip the current iteration, why not use continue:

for (i in 0..n) {
    if (someCond) {
        continue
    }
    // ...
}

旁注:.. 范围是包含的,所以要循环,例如一个大小为 n 的列表,你通常需要 0..(n - 1) 这更简单地使用 until:0 直到 n.

Side note: .. ranges are inclusive, so to loop through e.g. a list of size n you usually need 0..(n - 1) which is more simply done with until: 0 until n.

在您的具体情况下,您可以使用 windowed(Kotlin 1.2):

In your specific case, you can use windowed (Kotlin 1.2):

list.asSequence().filter { someCond }.windowed(2, 1, false).forEach { 
    val (first, second) = it
    // ...
}

asSequence 将列表转换为 Sequence,去除 filterwindowed 的开销,创建一个新的List(因为它们现在都将返回 Sequences).

asSequence will convert the list into a Sequence, removing the overhead of filter and windowed creating a new List (as they will now both return Sequences).

如果您希望下一对不包含前一对的最后一个元素,请改用 windowed(2, 2, false).

If you want the next pair to not include the last element of the previous pair, use windowed(2, 2, false) instead.

这篇关于在 Kotlin 中更改 for 循环索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆