【问题标题】:Kotlin: repeat n time while condition is trueKotlin:在条件为真时重复 n 次
【发布时间】:2020-10-16 11:20:14
【问题描述】:

我需要重复一段代码最多 n 次,但一旦条件为假就终止循环,如下所示:

val runs = 100
var ctr = 0
var condition = true

while (ctr++ < runs && condition) {
    //stuff and updates
}

这个逻辑可以用更惯用的方式表述吗,也许用repeat

【问题讨论】:

  • 我认为这是最干净的方法。 repeat 依赖于不支持 break 的 lambdas。

标签: loops kotlin conditional-statements idioms


【解决方案1】:

您可以嵌套 lambda 和 non-locally return to the outer one - 我不会说这很漂亮,但这是一个选项:

run loop@{
    repeat(100) {
        if(!condition) return@loop
        // stuff and updates
    }
}

【讨论】:

  • 是的,我不会使用它,但很高兴知道。
【解决方案2】:
val runs = 100
var condition = true


for(ctr in (0..runs)){
    if(condition){
        //stuff and updates
    }
}

【讨论】:

  • 循环仍然会通过每次迭代来检查条件是否为假。如果运行次数很大,那会浪费很多精力,并且条件很快就会变为错误。
猜你喜欢
  • 2018-07-04
  • 2018-02-14
  • 1970-01-01
  • 2013-05-11
  • 2014-11-24
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多