Python Logo

Kotlin Break/Continue


Kotlin Break and Continue: Controlling Loop Execution

The break and continue statements are essential control flow tools in Kotlin, providing mechanisms to terminate or skip iterations in loops. They allow for more granular control over the execution of loop bodies, enabling programmers to modify loop behavior based on specific conditions.

Break Statement: Terminating Loop Execution

The break statement immediately terminates the current loop, causing the loop body to stop executing and the program to exit the loop. It is typically used when a specific condition or termination criteria is met within the loop.

Syntax of the Break Statement:

break

 

Example of a Break Statement:

Consider a scenario where you want to stop searching for a specific element in a list once it is found:

val numbers = listOf(1, 2, 3, 4, 5, 6)

val target = 4

 

for (number in numbers) {

  if (number == target) {

    break

  }

  println("Checking number: $number")

}

 

println("Target element found.")

 

In this example, the break statement is used to terminate the for loop as soon as the target element 4 is found. Once the break statement is encountered, the loop body is skipped, and the program exits the loop.

Continue Statement: Skipping Loop Iteration

The continue statement skips the current iteration of the loop and immediately proceeds to the next iteration. It is used to conditionally bypass a specific iteration without terminating the entire loop.

Syntax of the Continue Statement:

continue

 

Example of a Continue Statement:

Consider a scenario where you want to skip processing even numbers in a list while iterating through the entire list:

val numbers = listOf(1, 2, 3, 4, 5, 6)

 

for (number in numbers) {

  if (number % 2 == 0) {

    continue

  }

  println("Processing odd number: $number")

}

 

In this example, the continue statement is used to skip the current iteration of the for loop whenever the current number is even. The loop proceeds to the next iteration, effectively skipping the processing of even numbers.

Conclusion

The break and continue statements are valuable tools for modifying loop behavior and controlling the execution of loops in Kotlin. They allow programmers to terminate loops early, skip specific iterations, and fine-tune the processing of data within loops. By effectively utilizing these control flow constructs, you can enhance the efficiency and flexibility of your Kotlin code.