Saturday, 16 December 2017

Kotlin: continue statement

continue statement skips the current iteration of loops(Ex: for, while, do-while loops). Just like break, continue also has two forms.
    1. unlabelled continue
    2. labelled continue

Unlabelled continue
    Syntax
        continue;

ContinueDemo.kt
fun main(args: Array<String>) {

 for (i in 1..10) {
  if (i % 2 != 0) {
   continue
  }
  print("$i ")
 }
}

Output
2 4 6 8 10

UnlabelledContinueInnerLoop.kt
fun main(args: Array<String>) {

 for (i in 1..5) {
  for(j in 1..10){
   if(j % 2 != 0){
    continue
   }
   print("$j ")
  }
  println()
 }
}

Output
2 4 6 8 10 
2 4 6 8 10 
2 4 6 8 10 
2 4 6 8 10 
2 4 6 8 10

Labelled Continue
Kotlin allows us to label any expression.

How to create a label?
Define an identifier followed by @ sign.

Ex:
outerLoop@, processState@

we can use continue statement with labels.

Syntax
continue@labelIdentifier

Ex
continue @outerLoop
continue @processState


ContinueLabelledDemo.kt
fun main(args: Array<String>) {

 outerLoop@ for (i in 1..5) {
  for (j in 1..10) {
   if (j > 5) {
    println()
    continue@outerLoop
   }
   print("$i ")
  }
 }
}


Output
1 1 1 1 1 
2 2 2 2 2 
3 3 3 3 3 
4 4 4 4 4 
5 5 5 5 5





Previous                                                 Next                                                 Home

No comments:

Post a Comment