The jump expressions in Kotlin are used to control the flow of the execution of the program. Kotlin supports the following jump expressions:
return
break
continue
return
expressionThe return
expression returns some value generated through an expression or value of a variable or a constant value.
This expression is often used to return values from a function after some execution.
In the following code snippet, we can see the use of the return
expression in Kotlin:
fun sum(n1: Int, n2: Int): Int { var result: Int = n1 + n2 // use of return expression return result } fun main(args : Array<String>) { var result = sum(5, 10) println(result) }
In the above code snippet:
sum()
that accepts two parameters, n1
and n2
, calculates its sum and returns the result using the return
expression in line 5.sum()
inside the function main()
, and print the result to the console.break
expressionThe break
expression is used to terminate the closest enclosing loop.
If there are multiple nested loops, and the break expression is in the most inner-loop, this expression will terminate only the most inner-most loop .
In the following code snippet, we can see the use of the break
expression in Kotlin:
fun main(args : Array<String>) { var n: Int = 6 for (i: Int in 1..n) { // use of break expression if (i == 4) break println("The value of i is: $i") } }
In the above code snippet, inside the main()
function:
n
and assign it some value.i
.break
expression to terminate the inner-loop if i = 4
.continue
expressionThe continue
expression is very similar to the break expression. The only difference is that the continued expression will only break or skip the current iteration.
In the following code snippet, we can see the use of the continue
expression in Kotlin:
fun main(args : Array<String>) { var n: Int = 6 for (i: Int in 1..n) { // use of break expression if (i == 4) continue println("The value of i is: $i") } }
In the above code snippet, inside the main()
function:
n
and assign it some value.i
.continue
expression to skip the iteration if i = 4
.RELATED TAGS
CONTRIBUTOR
View all Courses