Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A while loop in Kotlin is a control flow statement that repeatedly executes a block of code as long as a specified boolean condition evaluates to true. It functions as a pre-test loop, meaning the condition is evaluated before each iteration of the loop body.
while (condition) {
    // Loop body
}

Execution Mechanics

  1. The condition expression is evaluated. In Kotlin, this expression must strictly resolve to a Boolean type (true or false).
  2. If the condition evaluates to true, the statements within the loop body are executed sequentially.
  3. Upon reaching the end of the loop body, control flow jumps back to the condition evaluation.
  4. If the condition evaluates to false, the loop terminates immediately, and control passes to the next statement following the loop block.

The do-while Variant

Kotlin also provides the do-while loop, which operates as a post-test loop. The loop body is executed first, and the condition is evaluated afterward. This guarantees that the loop body will execute at least once, regardless of the initial state of the condition.
do {
    // Loop body
} while (condition)
Scoping Note: A distinct feature of Kotlin’s do-while loop is that variables declared inside the do block remain visible and accessible within the while condition expression.

Loop Control Statements

Kotlin provides structural jump expressions to alter the standard execution flow of while and do-while loops:
  • break: Immediately terminates the innermost enclosing loop. Control flow is transferred to the statement immediately following the loop.
  • continue: Skips the remaining statements in the current iteration of the loop body. Control flow is transferred directly back to the condition evaluation (in a while loop) or the post-test condition (in a do-while loop).

Labeled Jumps

For nested loops, Kotlin supports labels to explicitly define the target of break and continue expressions. A label is an identifier followed by the @ sign.
outerLoop@ while (conditionA) {
    while (conditionB) {
        if (exitCondition) {
            break@outerLoop // Terminates the outer loop, not just the inner loop
        }
        if (skipCondition) {
            continue@outerLoop // Skips to the next iteration of the outer loop
        }
    }
}
Master Kotlin with Deep Grasping Methodology!Learn More