Kotlin Break Continue Statement

10. Kotlin Break Continue 10.1 Kotlin Break Statement 10.2 Kotlin Continue Statement 10.3 Kotlin Return Statement


Kotlin Break Statement

Kotlin provides the break statement to implement the middle-existing control logic. The break statement causes the immediate exit from the body of the loop.
If we execute a break statement inside a for or while loop, control passes out of the loop.

Kotlin Continue Statement

The continue statement is similar to the break statement. When continue statement is executed, it stops the current iteration of the loop and continue with the next iteration of the loop. If we execute a continue statement inside a for loop, the control transfers control back to the top of the loop and the variable is set to the next value.

The statement in Kotlin is marked with a label. The label has the form of an identifier followed by the @ sign.

Example of Kotlin Break and Continue Statement
fun main(args : Array<String>)  { 
    loop@ for (n in 1..100) {
        println("$n")
        if (n == 10)
            break@loop
    }
    val l2 = listOf(10, 11, 12, 13)
    loop@ for (m in l2) {
        if(m == 11) {
            println("This is if block")
            break@loop
        } else {
            println("This is else block")
            continue@loop
        }
    }
}
Output of the above code:
1
2
3
4
5
6
7
8
9
10
This is else block
This is if block




Kotlin Return Statement

In Kotlin, the return expression returns some values from the nearest enclosing function or anonymous function.

Example of return statement
fun main(args : Array<String>)  { 
    val c = city()
    println("City = $c")
}
fun city() : String {
    return "Pune"
}
Output
City = Pune







Read more articles


General Knowledge



Learn Popular Language