How to "continue" or "break" in a `` `` in a while loop using Kotlin

I am transforming a large project into Kotlin. There were numerous problems. I am studying new Kotlin models - one of them. I hope I have a template that I can use to solve this problem.

Here is the code I'm trying to achieve. But break invalid in the when statement.

 while (!mStopped && c.moveToNext()) { val itemType = c.getInt() when (itemType) { 1, 2 -> { doSomething() if (condition) continue doSomethingElse() } } doTheLastStuff() } 

This is a very shortened version of the code. The Java source code had 100 lines inside the switch statements and a lot of continue and break .

What I'm trying to achieve is to continue execution in a while statement. What is the template for this in Kotlin

+5
source share
2 answers

You can use labels to continue / break the ie loop:

 myLoop@ while (!mStopped && c.hasNext()) { val itemType = c.next() when (itemType) { 1, 2 -> { doSomething() if (condition()) continue@myLoop doSomethingElse() } } doTheLastStuff() } 

Here is the relevant excerpt from the documentation:

Any expression in Kotlin can be tagged. Labels have the form of an identifier followed by an @ sign, for example: abc @, fooBar @ - valid labels (...) A break assigned to a label goes to the execution point to the right after the cycle marked with this label. Continuation continues until the next iteration of this loop.

+5
source

The problem here is that break and continue have special meaning inside the when statement, namely the violation and continuation of when itself, and not the surrounding loop. So far (kotlin 1.0) the syntax has not yet been resolved, so the function does not work, despite the reserved keywords.

To solve this problem, use the tags https://kotlinlang.org/docs/reference/returns.html#break-and-continue-labels :

 loop@ while (...) { when (itemType) { 1 -> continue@loop else -> break@loop } } 
+5
source

Source: https://habr.com/ru/post/1240267/


All Articles