Controlling Kotlin Loops with Break and Continue Keywords

Intro to 'break' and 'continue' Statements

Hello! Today, we'll delve into the break and continue commands in Kotlin's loop structures. Much like a stop or skip sign on a road, these commands control the execution flow within a loop. A break exits the entire loop, much like stopping our journey midway. Conversely, continue skips to the next loop iteration, akin to bypassing one road and taking the next on our journey. Are you ready to see these in action?

Understanding 'break' through an Example

Imagine sifting through books. Once you find the one you seek, you stop — that's the break keyword in action. Here's how one simulates that in Kotlin:

val bookStack = listOf("Java Basics", "Python for Beginners", "Web Development", "Learn Kotlin the Easy Way", "Advanced Algorithms") 

for (book in bookStack) {  // Assuming a list of books
    println("Checking book: $book")  // Print each book it checks
    if (book == "Learn Kotlin the Easy Way") { // If the book we want is found
        println("Found the book!") // Announce that we found the book
        break // Stop the book checking loop
    }
}

/*
 * Output:
 * Checking book: Java Basics
 * Checking book: Python for Beginners
 * Checking book: Web Development
 * Checking book: Learn Kotlin the Easy Way
 * Found the book!
 */

The break keyword stops the loop, thus saving unnecessary operations.

Understanding 'continue' through an Example

Next, let's get acquainted with continue through a sorting scenario. Suppose you want to ignore some items but allow the loop to run. Here's a Kotlin example:

val ballBox = listOf("blue", "red", "red", "blue", "blue", "red", "blue") 

for (ball in ballBox) { // Loop over each ball in the box
    if (ball == "red") { // If we find a red ball
        continue // Skip this ball and continue
    }
    // This will only print if ball is not red, thus 'continue' facilitates the skipping of red balls
    println("Sorted a $ball ball")
}

/*
 * Output:
 * Sorted a blue ball
 * Sorted a blue ball
 * Sorted a blue ball
 * Sorted a blue ball
 */ 

continue bypasses the current iteration, resuming the loop with the next, unlike break which terminates the whole loop.

Avoiding Pitfalls With 'break' and 'continue'

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal