Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Loop Control

Kotlin Loop Control

Loops make the same block of code execute repeatedly and are one of the most basic tools for controlling program flow.

Kotlin's loop syntax is very similar to Java's, but there's no traditional three-part for (int i = 0; i < n; i++); instead, you directly iterate over collections and ranges.

This page introduces the three loops for, while, and do...while, plus labeled jumps with break and continue, and finally non-local break and continue, stable since Kotlin 2.2.


for loop

The for loop iterates over any object that provides an iterator — collections, arrays, and ranges all work.

The syntax is for (element in iterable) { ... }; the element needs no declared type because the compiler infers it.

Example

// File path: LoopFor.kt

fun main

(

)

{

   

// listOf creates a read-only list

    val sites

=

listOf

(

"Runoob"

,

"www.runoob.com"

,

"RUNOOB"

)

   

// Take each element in turn; the type of the variable site is inferred as String

   

for

(

site in sites

)

{

        println

(

site

)

   

}

}

The output is as follows.



Runoob

www.runoob.com

RUNOOB

Iterating over an array works exactly the same way, because arrays also provide an iterator.

Example

fun main

(

)

{

   

// intArrayOf creates an Int array, avoiding boxing overhead

    val numbers

=

intArrayOf

(

10

,

20

,

30

)

   

for

(

number in numbers

)

{

        println

(

"Current element: $number"

)

   

}

}



当前元素:10

当前元素:20

当前元素:30

Kotlin's for only "takes out elements" and doesn't maintain a counter, so there's no problem of an infinite loop caused by forgetting i++.


Ranges and Steps

A range is itself an iterable object, constructed with .., until, downTo, and step.

Their boundary rules differ, and mixing them up is where beginners most often go wrong.

Syntax Meaning Iteration result
1..5 Closed range, includes both endpoints 1 2 3 4 5
1 until 5 Left-closed right-open, excludes the right endpoint 1 2 3 4
5 downTo 1 Descending from large to small 5 4 3 2 1
1..10 step 2 Specify a step, taking only odd numbers 1 3 5 7 9
1..<5 Half-open range, equivalent to until, stable since Kotlin 1.9 1 2 3 4

The following example compares these forms together.

Example

fun main

(

)

{

   

// Closed range 1..3: includes both endpoints

   

for

(

i in

1

..

3

)

print

(

"$i"

)

    println

(

"  => 1..3"

)

   

// until: includes the left endpoint, excludes the right

   

for

(

i in

1

until

3

)

print

(

"$i"

)

    println

(

"  => 1 until 3"

)

   

// downTo: descending from large to small

   

for

(

i in

3

downTo

1

)

print

(

"$i"

)

    println

(

"  => 3 downTo 1"

)

   

// step: specifies the step, which must be a positive number

   

for

(

i in

1

..

6

step

2

)

print

(

"$i"

)

    println

(

"  => 1..6 step 2"

)

   

// ..< Half-open range, stable since Kotlin 1.9

   

for

(

i in

1

..

<

3

)

print

(

"$i"

)

println

(

" => half-open range"

)

}



123  => 1..3

12  => 1 until 3

321  => 3 downTo 1

135  => 1..6 step 2

12  => 半开区间

Ranges aren't only for loops; you can also use in to test whether a value falls within a range, e.g. if (age in 18..60).

Tip:Iterating over a range directly is optimized by the compiler into a plain counting loop, with no object created for each element. But if you first write (1..1000).toList() and then iterate, it will actually create a list containing 1000 elements.


Iterating by Index: indices and withIndex

When you need both the index and the element value, use indices or the library function withIndex().

indices is a range of indices, while withIndex() returns a collection of indexed elements that can be used with destructuring declarations.

Example

fun main

(

)

{

    val sites

=

listOf

(

"Runoob"

,

"www.runoob.com"

,

"RUNOOB"

)

   

// indices returns the index range 0..2, suitable when you need to fetch values by index

   

for

(

i in sites.

indices

)

{

        println

(

"Index $i -> ${sites[i]}"

)

   

}

    println

(

"---"

)

   

// withIndex() gives both index and value; (index, value) is a destructuring declaration

   

for

(

(

index, value

)

in sites.

withIndex

(

)

)

{

        println

(

"$index: $value"

)

   

}

}



下标 0 -> Runoob

下标 1 -> www.runoob.com

下标 2 -> RUNOOB

---

0: Runoob

1: www.runoob.com

2: RUNOOB

A Map is also iterable, and you can destructure the key and value directly when iterating.

Example

fun main

(

)

{

   

// mapOf returns a Map that preserves insertion order

    val info

=

mapOf

(

"name"

to

"Runoob"

,

"site"

to

"www.runoob.com"

)

   

for

(

(

key, value

)

in info

)

{

        println

(

"$key = $value"

)

   

}

}



name = Runoob

site = www.runoob.com


while loop

while checks the condition first and executes the body only if it's true, so it may not run even once.

When the number of iterations is uncertain and depends on runtime state, while is more suitable than for.

Example

fun main

(

)

{

    var count

=

3

   

while

(

count

0

)

{

        println

(

"Countdown $count"

)

        count

--

           

// You must change the loop variable, otherwise it's an infinite loop

   

}

    println

(

"Loop ended"

)

}



倒计时 3

倒计时 2

倒计时 1

循环结束

If the condition is false from the start, the body never executes.

Example

fun main

(

)

{

    var count

=

0

   

while

(

count

0

)

{

        println

(

"This line will never be printed"

)

        count

--

   

}

    println

(

"Loop ended, count = $count"

)

}



循环结束,count = 0


do...while loop

do...while executes the body once before checking the condition, so the body runs at least once.

It suits scenarios of "do it once, then decide whether to continue", such as reading input or retrying an operation.

Example

fun main

(

)

{

    var count

=

0

   

do

{

        println

(

"Body executed: count = $count"

)

        count

++

   

}

while

(

count

<

0

)

// The condition is false from the start, but the body has already run once

    println

(

"Loop ended"

)

}



循环体执行:count = 0

循环结束

Note:The do...while while requires a semicolon after it, while ordinary while and for don't. This is one of the few places in Kotlin where a semicolon is mandatory.

Flowchart for choosing a loop construct: use for when the number of iterations or the object to iterate over is known, use while when condition-driven but the body may not execute even once, use do...while when condition-driven and it executes at least once; break ends the whole loop, continue skips the current iteration, and labels let a jump target an outer loop


break and continue

break immediately ends the innermost loop, while continue skips the current iteration and goes straight to the next.

Both only affect "the loop that most directly encloses them", unless used with a label.

Example

fun main

(

)

{

   

for

(

i in

1

..

10

)

{

       

if

(

i

==

3

)

continue

 

// Skip when i is 3, so the following println isn't executed

       

if

(

i

5

)

break

     

// End the whole loop when i is 6

        println

(

i

)

   

}

}



1

2

4

5

Jump expressions Purpose Typical scenario
break Terminate the nearest loop Exit early once the target is found, avoiding needless iteration
continue Skip the current iteration and move to the next Filter out elements that don't meet the condition
return Return from the nearest function End function execution and bring back a result

Labels and Labeled Jumps

A label is an identifier followed by @, written before a loop or lambda, used to specify a target for break, continue, or return.

Labeled jump control flow diagram: a for (j in 1..3) loop is nested inside an outer loop@ for loop; when j equals 2, break@loop jumps out of both levels at once to the end of the loop, while continue@loop follows a dashed line back to the next iteration of the outer loop

Without a label, break can only end the innermost loop; with a label you can break out of multiple nested levels at once.

Example

fun main

(

)

{

   

// loop@ is the label of the outer loop

    loop@

for

(

i in

1

..

3

)

{

       

for

(

j in

1

..

3

)

{

           

if

(

j

==

2

)

continue

@loop  

// Skip this iteration of the outer loop

           

if

(

i

==

3

)

break

@loop      

// End the outer loop directly

            println

(

"i = $i, j = $j"

)

       

}

   

}

    println

(

"Loop ended"

)

}



i = 1, j = 1

i = 2, j = 1

循环结束

A label can also be placed on a lambda, in which case return@label returns from that lambda rather than from the outer function.

Example

fun main

(

)

{

   

// Give the lambda an explicit label check

    val check

=

check@

{

value

:

Int

->

       

if

(

value

<

0

)

return

@check

"Negative"

"Non-negative number"

   

}

    println

(

check

(

5

)

)

    println

(

check

(

1

)

)

}



非负数

负数

Tip:Label names and variable names can be the same, but for readability it's recommended to give loops and lambdas meaningful label names, such as outer@、rows@。


Non-local break and continue (stable since 2.2)

Since Kotlin 2.2, break and continue inside an inline lambda can act directly on an outer loop; this is called a non-local jump.

It solves the problem of "wanting to skip or end an outer loop from inside a lambda", which previously required workarounds like return@label or an extra flag variable.

This feature was provided as a preview in Kotlin 2.1, requiring the compiler option -Xnon-local-break-continue; from 2.2 on it's available by default (KT-1436).

Example

fun main

(

)

{

    val numbers

=

listOf

(

1

,

null

,

3

,

null

,

5

)

   

for

(

number in numbers

)

{

       

// run is an inline function, so the continue in its lambda acts on the outer for loop

        val value

=

number

?:

run

{

            println

(

"Encountered null, skipping this iteration"

)

           

continue

       

}

        println

(

"Processing number: $value"

)

   

}

    println

(

"Loop ended"

)

}



处理数字:1

遇到 null,跳过本次循环

处理数字:3

遇到 null,跳过本次循环

处理数字:5

循环结束

break can be used the same way, directly ending the entire outer loop.

Example

fun main

(

)

{

    val numbers

=

listOf

(

1

,

2

,

3

,

4

,

5

)

   

for

(

number in numbers

)

{

        run

{

           

if

(

number

==

4

)

break

 

// Non-local break: ends the outer for loop

       

}

        println

(

"Current number: $number"

)

   

}

    println

(

"Loop ended"

)

}



当前数字:1

当前数字:2

当前数字:3

循环结束

Note:Non-local break/continue only works for lambdas passed to inline functions, e.g. the lambda of run、let、forEach an inline function such as run. If a lambda is saved into a variable and then passed to a regular function, such jumps are still not allowed, because the compiler can't guarantee it executes in place.


return and Labeled Returns

return normally returns from the nearest function, but in a lambda you must distinguish two cases: returning from the outer function, or only ending this lambda.

return@label returns only from the labeled lambda, which has an effect similar to continue inside a lambda.

Example

fun main

(

)

{

    val numbers

=

listOf

(

1

,

2

,

0

,

4

)

   

// return@forEach only ends this lambda call, equivalent to skipping 0

    numbers.

forEach

{

       

if

(

it

==

0

)

return

@

forEach

        println

(

"forEach:$it"

)

   

}

    println

(

"---"

)

   

// You can achieve the same effect with a for loop plus continue

   

for

(

number in numbers

)

{

       

if

(

number

==

0

)

continue

        println

(

"for:$number"

)

   

}

}



forEach:1

forEach:2

forEach:4

---

for:1

for:2

for:4

The label name can be omitted, in which case the compiler uses the name of the function receiving the lambda as an implicit label — so the forEach in return@forEach is an implicit label.

Note:forEach is an inline function, so writing return directly inside its lambda returns from the outer function rather than just ending this iteration. These non-local return rules are explained in detail in the article "Kotlin Inline Functions and reified"; in everyday code, to skip only the current element use return@forEach。


Common questions

Below are a few questions beginners often encounter.

Problem Description
Do ranges in a for loop create objects Iterating over 1..10 directly is optimized into a counting loop with no extra objects; converting to a List first and then iterating creates a collection
Writing continue inside forEach is an error forEach's lambda isn't a loop; use return@forEach instead, or switch to a for loop
Why is there a semicolon after do...while Kotlin's grammar requires a semicolon after while (condition); this is one of the few places where the semicolon can't be omitted
Where to place a label A label goes immediately before the object it labels, e.g. loop@ for (...), name@ { ... }
Non-local break errors in older versions This feature was a preview in 2.1 and stable from 2.2; in older versions use labeled returns or a flag variable instead