Friday 15 December 2017

Kotlin: break statement

'break' statement is used to come out of the loop. 'break' statement can be used in two forms.
         a. unlabeled break
         b. labeled break

unlabeled break
Unlabeled break is used to come out from nearest closing loop.

Syntax
break

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

 for (i in 1..10) {
  println(i)

  if (i == 5) {
   break
  }
 }
}

Output
1
2
3
4
5

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

 for (i in 1..5) {
  for (j in 1..i) {
   print("$j")
  }
  println()
 }
}

Output
1
12
123
1234
12345

Labelled break
Kotlin allows us to label any expression.

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

Ex:
outerLoop@, processState@

By specifying the label, we can come out of the label.

Syntax
break@labelIdentifier

Ex
break@outerLoop
break@processState


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

 var counter: Int = 0;

 outerLoop@ for (i in 1..5) {
  for (j in 1..i) {
   counter++
   print("$j")

   if (counter == 6) {
    println("\nBreaking out of the outer loop")
    break@outerLoop
   }
  }
  println()
 }
}


Output
1
12
123
Breaking out of the outer loop




Previous                                                 Next                                                 Home

No comments:

Post a Comment