Left Index

Kotlin Continue

In Kotlin, continue statement is used to repeat the loop. It continues the current flow of the program and skips the remaining code at specified condition.


Note: The continue statement within a nested loop only affects the inner loop.


Syntax for continue

Syntax:
for(item in Collection) {
	if(condition) {
		continue;
	}
	
	// your bussiness logic
}

Let's create and example and try to understand continue

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	for(item in 1..10) {
		if(item <= 5) {
			continue;
		}
		
		print("${item}, ")
	}
}
Output:
6, 7, 8, 9, 10, 

Kotlin Labeled continue Expression

continue can also be used to skip the iteration of the desired loop (can be outer loop) by using continue labels. Label in Kotlin starts with an identifier which is followed by @.


Let's have an example, where outerloop@ is a label marked at outer while loop. Now, by using continue with the label (continue@outerloop in this case), you can skip the execution of codes of the specific loop for that iteration.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	outerloop@ for(item in 1..2) {
		for(item1 in 20 downTo 14 step 2) {
			if(item ==2 && item1 == 18) {
				continue@outerloop
			}
			
			println("OuterLoop: ${item}, innerLoop: ${item1}")
		}
		
		println()
	}
}

In above example when item == 2 and item1 == 18 than control move to again outer loop.

Output:
OuterLoop: 1, innerLoop: 20
OuterLoop: 1, innerLoop: 18
OuterLoop: 1, innerLoop: 16
OuterLoop: 1, innerLoop: 14

OuterLoop: 2, innerLoop: 20