Kotlin – Break & Continue

Kotlin Break Expression

Kotlin break Expression is used to come out of a loop once a certain condition is met. This loop could be a forwhile or do…while loop.

Syntax

Let’s check the syntax to terminate various types of loop to come out of them:

// Using break in for loop
for (...) {
   if(test){
      break
   } 
}

// Using break in while loop
while (condition) {
   if(test){
      break
   } 
}

// Using break in do...while loop
do {
   if(test){
      break
   } 
}while(condition)

If test expression is evaluated to true, break statment is executed which terminates the loop and program continues to execute just after the loop statment.

Example

Following is an example where the while loop terminates when counter variable i value becomes 3:

fun main(args: Array<String>) {
   var i = 0;
   while (i++ < 100) {
      println(i)
      if( i == 3 ){
         break
      }

   }
}

When you run the above Kotlin program, it will generate the following output:

1
2
3

Kotlin Labeled Break Statement

Kotlin label is the form of identifier followed by the @ sign, for example test@ or outer@. To make any Kotlin Expression as labeled one, we just need to put a label in front of the expression.

outerLoop@ for (i in 1..100) {
    // ...
}

Kotlin labeled break statement is used to terminate the specific loop. This is done by using break expression with @ sign followed by label name (break@LabelName).

fun main(args: Array<String>) {
    outerLoop@ for (i in 1..3) {  
        innerLoop@ for (j in 1..3) {  
            println("i = $i and j = $j")  
            if (i == 2){  
                break@outerLoop
            }  
        }  
    }  
}

When you run the above Kotlin program, it will generate the following output:

i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 2 and j = 1

Kotlin continue Expression

It is almost always used with if…else construct. For example,

while (testExpression1) {

    // codes1
    if (testExpression2) {
        continue
    }
    // codes2
}

If the testExpression2 is evaluated to truecontinue is executed which skips all the codes inside while loop after it for that iteration.

How continue expression works in Kotlin?

Example: Kotlin continue

fun main(args: Array<String>) {

    for (i in 1..5) {
        println("$i Always printed.")
        if (i > 1 && i < 5) {
            continue
        }
        println("$i Not always printed.")
    }
}

When you run the program, the output will be:

1 Always printed.
1 Not always printed.
2 Always printed.
3 Always printed.
4 Always printed.
5 Always printed.
5 Not always printed.

When the value of i is greater than 1 and less than 5, continue is executed, which skips the execution of

println("$i Not always printed.")

statement.

However, the statement

println("$i Always printed.")

is executed in each iteration of the loop because this statement exists before the continue construct.

Kotlin Labeled continue

What you have learned till now is unlabeled form of continue, which skips current iteration of the nearest enclosing loop. continue can also be used to skip the iteration of the desired loop (can be outer loop) by using continue labels.


How labeled continue works?

How labeled continue works?

Label in Kotlin starts with an identifier which is followed by @.

Here, 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: labeled continue

fun main(args: Array<String>) {

    here@ for (i in 1..5) {
        for (j in 1..4) {
            if (i == 3 || j == 2)
                continue@here
            println("i = $i; j = $j")
        }
    }
}

When you run the program, the output will be:

i = 1; j = 1
i = 2; j = 1
i = 4; j = 1
i = 5; j = 1

The use of labeled continue is often discouraged as it makes your code hard to understand. If you are in a situation where you have to use labeled continue, refactor your code and try to solve it in a different way to make it more readable.

I hope you found what you were looking for from this tutorial. If you want more Kotlin tutorials like this, then do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂

Leave a Comment

Your email address will not be published.