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.
Page Contents
- 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)
}
}
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")
}
}
}
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)
}
}
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")
}
}
}
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)
}