What are the jump expressions in Kotlin?
Overview
The jump expressions in Kotlin are used to control the flow of the execution of the program. Kotlin supports the following jump expressions:
returnbreakcontinue
1. The return expression
The 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.
Example
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 expressionreturn result}fun main(args : Array<String>) {var result = sum(5, 10)println(result)}
Explanation
In the above code snippet:
- Lines 1 to 6: We define a function
sum()that accepts two parameters,n1andn2, calculates its sum and returns the result using thereturnexpression in line 5. - Lines 8 to 11: We invoke the function
sum()inside the functionmain(), and print the result to the console.
2. The break expression
The 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 .
Example
In the following code snippet, we can see the use of the break expression in Kotlin:
fun main(args : Array<String>) {var n: Int = 6for (i: Int in 1..n) {// use of break expressionif (i == 4)breakprintln("The value of i is: $i")}}
Explanation
In the above code snippet, inside the main() function:
- Line 2: We declare a variable
nand assign it some value. - Lines 4 to 12: We use a nested to loop and print the value of
i. - Line 7: We use the
breakexpression to terminate the inner-loop ifi = 4.
3. The continue expression
The 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.
Example
In the following code snippet, we can see the use of the continue expression in Kotlin:
fun main(args : Array<String>) {var n: Int = 6for (i: Int in 1..n) {// use of break expressionif (i == 4)continueprintln("The value of i is: $i")}}
Explanation
In the above code snippet, inside the main() function:
- Line 2: We declare a variable
nand assign it some value. - Lines 4 to 12: We use a nested to loop and print the value of
i. - Line 7: We use the
continueexpression to skip the iteration ifi = 4.