Kotlin Return and jump

These are the jump expression are used to control the flow of program execution.

  • return
  • break
  • continue

return : By default returns from the nearest enclosing function or anonymous function

continue : Proceeds to the next step of the nearest enclosing loop

break : It is used to  terminates the nearest enclosing loop. it is used to bring the control out of the block.

For example

for(..){  
       //if condition true it terminates the loop 
       if(checkCondition){  
           break;  
       }  
}  

Example :

fun main(args: Array<String>) {  
    for (i in 1..5) {  
        if (i == 4) {
            println("terminated from loop")
            break  
        }  
        println(i)  
    }  
}

Output

1
2
3
terminated from loop

Kotlin Labeled break Expression

labeled break is used to terminate to a desired loop when certain condition is satisfied and Unlabeled break is used to terminate to the closest enclosing loop when a certain condition is satisfied.

this can be used by @sign is called label e.g.- inner@, outer@ etc.

Labeled break in for loop

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

Output

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

In the above example when the value of i becomes 2 labeled break will execute and terminate the body of labeled expression.

 Labeled break in while loop

outer@ while(condition) {
      // code
      inner@ while(condition) {
            // code
            if( condition) {
               break @outer
            } 
      }
  }
fun main(args: Array<String>) {
    var i = 4
    outer@ while (i > 0) {
        var j = 3
        inner@ while (j > 0) {
            if (i==2)
                break@outer
            println("i = $i, j = $j")
            j--
        }
        i--
    }
}

Output

i = 4, j = 3
i = 4, j = 2
i = 4, j = 1
i = 3, j = 3
i = 3, j = 2
i = 3, j = 1

When value of of i becomes 2 outer loop will be terminated by break.