I am converting a large project to Kotlin. There have been numerous challenges. Me learning the new patterns of Kotlin is one of them. Hopefully there is a pattern I can use to resolve this one.
Here is the code I am attempting to achieve. But, continue
and break
are not valid in a when
statement.
while (!mStopped && c.moveToNext()) {
val itemType = c.getInt()
when (itemType) {
1, 2 -> {
doSomething()
if (condition)
continue
doSomethingElse()
}
}
doTheLastStuff()
}
This is a very cut-down version of the code. The original java code had 100's of lines inside the switch statements, and lots of continue
's and break
's.
What I am trying to achieve is to continue execution back at the while
statement. What is the pattern for doing this in Kotlin
You can use labels to continue/break the loop i.e:
myLoop@ while (!mStopped && c.hasNext()) {
val itemType = c.next()
when (itemType) {
1, 2 -> {
doSomething()
if (condition())
continue@myLoop
doSomethingElse()
}
}
doTheLastStuff()
}
Here's is a relevant excerpt from documentation:
Any expression in Kotlin may be marked with a label. Labels have the form of an identifier followed by the @ sign, for example: abc@, fooBar@ are valid labels(...) A break qualified with a label jumps to the execution point right after the loop marked with that label. A continue proceeds to the next iteration of that loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With