Introduction
In this blog, we will discuss jump expressions. Jump expressions are used to control the flow of execution of code. We will discuss how and where to use a particular jump expression. If you are new to Kotlin and have yet to write your first program in the language, check out our other article on Kotlin syntax and first program.
Kotlin has three structural jump expressions: return, break and continue. We will also look at labels. Labels are identifier that includes the @ sign followed by a label name, and you can place a label in front of any expression to make it a label. We will also see how they can be used with break and continue expressions to alter the control flow of the program.
Return
It is generally used in function declarations to return values after a function has been executed. A return statement terminates a function's execution and hands control back to the calling function. Execution continues in the calling function at the point immediately following the call.
In the program below, we calculate the sum of all the array’s elements and return it as the function’s output.
// Function to calculate the sum of all the array elements
fun calculateSum(arr: Array<Int>) : Int {
var sum=0 // Initialising the variable sum with zero value
for(i in arr){ // Traversing the array
sum+=i
}
return sum // Returning Sum
}
fun main(){
var arr = arrayOf<Int>(1,2,3,4) // Initialising an array
var res= calculateSum(arr) // Calling calculateSum function to calculate the sum of all elements of array
print(res)
}
Output:
10
In the below example, the function will return when the total sum exceeds 5. In the previous example, we used a return statement to return the function's output, but in this case, we will use a return statement to stop the function's execution.
// Function to calculate the sum of all the elements of an array.
// This function will return when the total sum exceeds 5.
fun calculateSum2(arr: Array<Int>){
var sum=0 // Initialising the variable sum with zero value
for(i in arr){ // Traversing the array
if(sum>5)return // Function returns if sum goes above 5
sum+=i
println(sum) // Printing the current sum
}
}
fun main(){
var arr = arrayOf<Int>(1,1,2,4,5) // Initialising an array
// Calling calculateSum2 function to find the sum of the array. It will return when the sum exceeds 5.
calculateSum2(arr)
}
Output:
1
2
4
8
So, this is how the return statement works.




