How do I do a “break” or “continue” when in a functional loop within Kotlin?

后端 未结 4 1916
长发绾君心
长发绾君心 2020-12-04 16:09

In Kotlin, I cannot do a break or continue within a function loop and my lambda -- like I can from a normal for loop. For example, th

4条回答
  •  粉色の甜心
    2020-12-04 17:12

    If there's a need to use continue or break, it is not ideal to use forEach compare to normal for-loop

    If you really like to chain your command, and perform like a for-loop, use the normal functional chain, instead of forLoop

    E.g. for

        for(i in 0 until 100 step 3) {
            if (i == 6) continue
            if (i == 60) break
            println(i)
        }
    

    Use map as for-loop, filterNot as continue, and asSequence() & first for break

        (0 until 100 step 3).asSequence()
                .filterNot { it == 6 }
                .map { println(it); it }
                .first { it == 60 }
    

提交回复
热议问题