Kotlin Break/Continue
Break and continue statements are control flow tools in programming languages that allow for more flexibility and efficiency in code execution.
Break Statement
The `break` statement terminates a loop prematurely, regardless of whether the loop condition has been satisfied. Once the `break` statement is encountered, the program exits the loop and resumes execution from the next line of code after the loop block.
Syntax of the Break Statement
In Kotlin, the break statement can be used both with and without labels.
- Without Label:
In this example, the break statement is used without a label. It terminates the inner loop when `i` is equal to 2 and `j` is equal to 2.
- With Label:
Here, the `outerLoop` label is used to break out of the outer loop when `i` and `j` are both equal to 2.
Example of Using the Break Statement in a Loop
In this example, the loop iterates from 1 to 10. However, when the value of `i` becomes 5, the break statement is executed, and the loop terminates. As a result, only the numbers 1, 2, 3, and 4 will be printed.
Continue Statement
The `continue` statement skips the remaining code within a loop iteration and moves on to the next iteration. This is helpful when certain conditions should result in skipping the current iteration.
Syntax of the Continue Statement
- Without Label:
When the value of `i` is 3, the continue statement is executed, and the remaining code within that iteration is skipped.
- With Label:
Here, the `outerLoop` label is used to skip the current iteration of the outer loop when `i` and `j` are both equal to 2.
Skipping Iterations with Continue
In Kotlin, skipping iterations within a `for` loop can be accomplished by using the unlabeled continue statement.
In this example, the loop will print only the odd numbers between 1 and 10 because the continue statement skips the even numbers.
Difference Between Break and Continue Statements
- Break: Terminates the nearest enclosing loop completely.
- Continue: Skips the current iteration and proceeds to the next iteration.
Advanced Usages of Break/Continue in Kotlin
Using Labels with Break/Continue Statements
Labels in Kotlin provide a way to control the flow of nested loops more precisely.
- Breaking out of a labeled loop:
Here, the loop labeled `loop` is terminated entirely when `i` and `j` are both equal to 5.
- Continuing a labeled loop:
In this example, the iteration of the outer loop is skipped when `i` and `j` are both equal to 2, but the outer loop continues with the next iteration.
By using these statements effectively, you can better control the flow of your Kotlin programs, making them more efficient and easier to read and maintain.