Compare while and do-while in Kotlin, and explain when you'd choose a while loop over a for/range loop. What's special about the scope of variables declared in a do-while condition?
answer
- while = test first (0+), do-while = run first (1+)
- do-body vars visible in while condition
- loops are NOT expressions
- while for unknown-count / irregular stepping
- for/range for fixed-stride counts
basics
~10 swhile checks the condition before running the body, so it may run zero times. do-while runs the body once first, then checks. Use while when the number of steps isn't a simple count.
solid answer
~40 s`while (cond) { ... }` is pre-tested: it evaluates `cond` first and may execute zero times. `do { ... } while (cond)` is post-tested: the body always runs at least once, then `cond` is checked. You choose `while`/`do-while` over a `for`/range loop when iteration isn't a fixed-stride count — e.g. reading until end-of-stream, polling, exponential stepping (`i *= 2`), or consuming a queue until empty. A Kotlin-specific detail: a variable declared inside the `do` body is **visible in the `do-while` condition**, because the condition is considered part of the same block — `do { val x = next() } while (x != null)` compiles, which is unusual compared to many languages. Neither `while` nor `do-while` is an expression (they yield no value), unlike `if`/`when`.
code
kotlin · 9 lines// do-while: variable from body usable in condition
do {
val token = lexer.next()
emit(token)
} while (token.type != EOF)
// while for irregular stepping (no fixed range)
var i = 1
while (i <= n) { i *= 2 }go deeper
Knows while tests first (can run 0 times) and do-while runs at least once.
Chooses while over for when stepping is irregular or the bound is non-numeric, and knows loops aren't expressions.
Cites the do-body-variable-in-condition scope rule and gives concrete I/O/polling use cases.
Discusses readability/maintainability tradeoffs of while vs functional alternatives (generateSequence, takeWhile) and loop-as-statement design.
## while (pre-tested) ```kotlin while (condition) { // may run 0..N times } ``` The condition is checked **before** each iteration, including the first — so the body can execute zero times. ## do-while (post-tested) ```kotlin do { // runs at least once } while (condition) ``` The body runs first, **then** the condition is checked. Guarantees at least one execution. Good for 'try once, repeat if needed' patterns (menus, retries, read-then-check). ## Special scope rule In Kotlin, variables declared in the `do` block are **in scope in the `while` condition**: ```kotlin do { val line = reader.readLine() process(line) } while (line != null) // line is visible here! ``` This is intentional and convenient — the condition is treated as part of the loop's block. Many languages don't allow this. ## When to prefer while over for/range Use `for (i in range)` when you have a **known, fixed-stride** count. Reach for `while`/`do-while` when: - The end condition isn't a numeric bound: `while (scanner.hasNext())`, `while (queue.isNotEmpty())`. - The update isn't a constant stride: `var i = 1; while (i < n) { i *= 2 }`. - You poll or retry until success. ```kotlin var n = 100 while (n > 1) { n = if (n % 2 == 0) n / 2 else 3 * n + 1 } // Collatz ``` ## Not expressions `while` and `do-while` produce no value (type `Unit`); you cannot write `val x = while(...)`. Only `if`, `when`, and `try` are expressions in Kotlin. `break`/`continue` (and labeled forms) work inside both — but labeled break/continue is a sibling topic. ## Summary - `while` = check first (0+ runs); `do-while` = run first (1+ runs). - `do`-body variables are visible in the `while` condition. - Use them when iteration isn't a fixed-stride numeric range.
- Can a while loop be used as an expression to assign a value?No. while and do-while always yield Unit; only if, when, and try are expressions in Kotlin.
- Why does do { val x = ... } while (x != null) compile?Kotlin treats the do-while condition as part of the loop's block, so variables declared in the body are in scope in the condition.
while is checking the weather before stepping outside; do-while is stepping outside, then deciding whether to go back in.
saying these in an interview costs you the question
- Saying do-while may run zero times
- Treating while as an expression that returns a value
- Not knowing do-body variables are visible in the condition
- Forcing a for/range loop where the end condition isn't a numeric bound