Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to `continue` or `break` in a `when` statement inside a `while` loop using Kotlin [duplicate]

Tags:

kotlin

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

like image 534
Brian Donovan-Smith Avatar asked Jan 10 '16 09:01

Brian Donovan-Smith


1 Answers

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.

like image 108
miensol Avatar answered Sep 20 '22 18:09

miensol