Jump expressions in Kotlin

In this tutorial, we will learn about Jump expressions in Kotlin. The main use of all these three jump expressions is to move the cursor on the different statement in code. There are a total of three jump expressions available in Kotlin.

  • break
  • continue
  • return

Break expression:

The break expression is used to terminates the nearest enclosing loop. Here is an example o break expression. Break expression in Kotlin can be used with or without a label.

Example Program(without a Label):

fun main(args: Array<String>) {  
    for (num in 1..10) {  
        if (num == 5) {  
            break  
        }  
        println(num)  
    }  
}  

Output:

1
2
3
4

Example Program(with a label):

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

Output:

1  1
1  2
1  3
1  4
1  5

Continue expression:

Continue expression is mainly used to skip an iteration of the loop. Continue expression can be used with or without a label.

Example Program(without a label):

fun main(args: Array<String>) {  
    for (num in 1..5) {  
        if (num == 3) {  
            continue  
        }  
        println(num)  
    }  
}  

Output:

1
2
4
5

Example Program(with a label):

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

Output:

1  1
1  2
1  3
3  1
3  2
3  3

Return expression:

The return statement is used to return some value from a function. We normally write it as the last statement in the function. Here is an example program of return expression check it out.

Example Program:

//defining function
fun addition(num1: Int, num2: Int): Int{
  return num1+num2
}
fun main (args: Array<String>){
    var ans=addition(10,20) //calling the function
    println("Ans = "+ans)
}

Output:

Ans = 30
Spread the love